def read_irs(self, x, y, o, r, objects): # data vis_sensors_domain = [] ir_reading = [] # for each sensor for ir_angle in self.ir_angles: ir_val = 0 min_dist = self.ray_length # location and orientation according to agent ir_o = geometry.force_angle(o + ir_angle) ir_x = x + r * np.cos(ir_o) ir_y = y + r * np.sin(ir_o) # define visual domain arc_start = ir_o + self.beam_angles[0] arc_end = ir_o + self.beam_angles[1] # to be sure the angle is counter-clockwise if arc_start > arc_end: arc_end += np.radians(360) # get arc angle points and force angles arc_points = np.linspace(arc_start, arc_end, self.s_points) arc_angles = np.array( [geometry.force_angle(oi) for oi in arc_points]) # get the arc coordinates and create polygon arc_x = ir_x + self.ray_length * np.cos(arc_angles) arc_y = ir_y + self.ray_length * np.sin(arc_angles) vis_coords = [(ir_x, ir_y)] [vis_coords.append((xi, yi)) for xi, yi in zip(arc_x, arc_y)] vis_domain = Polygon(vis_coords) vis_sensors_domain.append(vis_domain) # check for intersections for w in objects["walls"]: wall = LineString([(w.xmin, w.ymin), (w.xmax, w.ymax)]) if vis_domain.intersects(wall): dist = Point(ir_x, ir_y).distance(vis_domain.intersection(wall)) if dist < min_dist: min_dist = dist round_objects = objects["trees"] + objects["agents"] for obj in round_objects: obj_loc = Point(obj.x, obj.y) obj_space = obj_loc.buffer(obj.r) if vis_domain.intersects(obj_space): dist = Point(ir_x, ir_y).distance( vis_domain.intersection(obj_space)) if dist < min_dist: min_dist = dist # get ir value if min_dist < self.ray_length: # IR reading for a given distance from empirical fitting data # gaussian 3371*e^(-(d/8.5)^2) fits well [0, 3500] k = -1 * ((dist / 8.5)**2) ir_val = (3371 * np.exp(k)) / 3500 ir_reading.append(ir_val) self.sensory_domain["vis"].append(vis_sensors_domain) return ir_reading
def read_olf(self, x, y, o, r, objects): # sensor location-orientation olf_x = x + r * np.cos(o) olf_y = y + r * np.sin(o) olf_val = 0 # define sensor domain (polygon) arc_start = o + self.olf_angles[0] arc_end = o + self.olf_angles[1] # to be sure the angle is counter-clockwise if arc_start > arc_end: arc_end += np.radians(360) # get arc angle points and force angles arc_points = np.linspace(arc_start, arc_end, self.s_points) arc_angles = np.array([geometry.force_angle(oi) for oi in arc_points]) # get the arc coordinates and create polygon arc_x = olf_x + self.olf_range * np.cos(arc_angles) arc_y = olf_y + self.olf_range * np.sin(arc_angles) olf_coords = [(olf_x, olf_y)] [olf_coords.append((xi, yi)) for xi, yi in zip(arc_x, arc_y)] olf_domain = Polygon(olf_coords) self.sensory_domain["olf"].append(olf_domain) # check for each tree min_dist = self.olf_range trees = objects["trees"] for tx in trees: tree_loc = Point(tx.x, tx.y) tree_space = tree_loc.buffer(tx.r) if olf_domain.intersects(tree_space): dist = Point(olf_x, olf_y).distance( olf_domain.intersection(tree_space)) if dist <= min_dist: olf_val = (1 / np.exp(min_dist / self.olf_range))**2 return olf_val
def feed(self, objects): # "mouth" location fx = self.x + self.r * np.cos(self.o) fy = self.y + self.r * np.sin(self.o) # feeding area: arc arc_start = self.o - np.radians(self.feeding_angle / 2) arc_end = self.o + np.radians(self.feeding_angle / 2) # force counter-clockwise if arc_start > arc_end: arc_end += np.radians(360) # get arc angle points and force angles arc_points = np.linspace(arc_start, arc_end, self.genotype.s_points) arc_angles = np.array([geometry.force_angle(oi) for oi in arc_points]) # get the arc coordinates and create polygon arc_x = fx + self.olf_range * np.cos(arc_angles) arc_y = fy + self.olf_range * np.sin(arc_angles) feeding_coords = [(fx, fy)] [feeding_coords.append((xi, yi)) for xi, yi in zip(arc_x, arc_y)] feeding_area = Polygon(feeding_coords) # check for trees to feed feeding = False trees = objects["trees"] for tree in trees: if feeding_area.intersects(tree): feeding = True feed_rate = self.feed_rate * (1 / np.exp(dist / self.feed_range)) self.feeding_states.append([feeding_area, feeding])
def crop_ground_truths(x, y, tile_size, gt_coords, gt_polys): """ Takes a tile location+dimensions and finds all ground truths that intersect that tile param x: the x-coord of the top-left vertex of the tile param y: the y-coord of the top-left vertex of the tile param tile_size: the length of the tile side param gt_coords: a list of the ground truths in the form of the vertices param gt_polys: a list of the ground truths in the form of Shapely polygons returns: a list of shifted ground truth coordinates that intersect the tile """ tile = Polygon([(x, y), (x, y + tile_size), (x + tile_size, y + tile_size), (x + tile_size, y)]) intersects_tile = [tile.intersects(gt) for gt in gt_polys] intersects_tile = np.asarray(intersects_tile) keep_indices = np.argwhere(intersects_tile) # Hack because squeezing a 1x1 matrix will return a scalar, # which will break the code if (len(keep_indices) == 1): keep_indices = keep_indices[0] else: keep_indices = np.squeeze(keep_indices) keep_gt = np.asarray(gt_coords[:, :, keep_indices]) keep_gt[:, 0, :] = keep_gt[:, 0, :] - np.asarray([x]) keep_gt[:, 1, :] = keep_gt[:, 1, :] - np.asarray([y]) # TODO: Sort ground truths by area for marking shrunk away don't # care regions correctly when generating targets. return keep_gt
def cropGroundTruths(x, y, tile_size, gt_coords, gt_polys): """ Takes a tile location+dimensions and finds all ground truths that intersect that tile param x: the x-coord of the top-left vertex of the tile param y: the y-coord of the top-left vertex of the tile param tile_size: the length of the tile side param gt_coords: a list of the ground truths in the form of the vertices param gt_polys: a list of the ground truths in the form of Shapely polygons returns: a list of shifted ground truths that intersect the tile """ tile = Polygon([(x, y), (x, y + tile_size), (x + tile_size, y + tile_size), (x + tile_size, y)]) intersects_tile = [tile.intersects(gt) for gt in gt_polys] intersects_tile = np.asarray(intersects_tile) keep_indices = np.squeeze(np.argwhere(intersects_tile)) keep_gt = np.asarray(gt_coords[:, :, keep_indices]) print len(keep_gt), len(keep_gt[0]), keep_gt keep_gt[:, 0, :] = keep_gt[:, 0, :] - np.asarray([x]) keep_gt[:, 1, :] = keep_gt[:, 1, :] - np.asarray([y]) # TODO: Need to sort ground truths by area return keep_gt
def areDoorsInRoom2021(level): level_doorfix = level.copy() # for each room in level, check each door; for room in level_doorfix['rooms']: # inDatabase Check: for o in room['objList']: if o['modelId'] in sk_to_ali or o['modelId'] in suncg: o['inDatabase'] = True else: o['inDatabase'] = False if not os.path.exists('room/{}/{}f.obj'.format(room['origin'], room['modelId'])): continue try: room_meta = p2d('.', 'room/{}/{}f.obj'.format(room['origin'], room['modelId'])) room_polygon = Polygon(room_meta[:, 0:2]) # requires python library 'shapely' except Exception as e: print(e) continue for r in level['rooms']: for obj in r['objList']: if obj is None: continue if 'coarseSemantic' not in obj: continue if obj['coarseSemantic'] not in ['door', 'Door']: continue block = windoorblock_f(obj) block_polygon = Polygon(block['windoorbb']).buffer(.03) # for this time, we do not duplicate doors, instead we add roomIds to the obj. if room_polygon.intersects(block_polygon): if 'roomIds' not in obj: obj['roomIds'] = [] obj['roomIds'].append(room['roomId']) return level_doorfix
def roi_overlap(ROIs1, ROIs2, param1, param2, im1_shape, im2_shape, thr_ovlp=0.5, pplot=False, im1=None): """ rotate/translate rois ROI1 and ROI2 by parameters param1 and param2, and then test which ROIs overlap """ ROIs1_trans = rottrans_rois(ROIs1, param1[0], param1[1], param1[2], im1_shape[0], im1_shape[1]) ROIs2_trans = rottrans_rois(ROIs2, param2[0], param2[1], param2[2], im2_shape[0], im2_shape[1]) # NOTE: for plotting the variable im1 is missing if pplot: plt.figure() axes = plt.subplot(111) axes.imshow(im1, cmap='gray') draw_rois(ROIs1, axes, 'red') draw_rois(ROIs2_trans, axes, 'green') plt.show(block=False) # test which ROIs overlap ri = 0 roi_map = {} for r in ROIs1_trans: (x0, y0) = (r[0][0], r[1][0]) polyg1 = Polygon(list(zip(r[0], r[1])) + [(x0, y0)]) si = 0 for s in ROIs2_trans: (x0, y0) = (s[0][0], s[1][0]) polyg2 = Polygon(list(zip(s[0], s[1])) + [(x0, y0)]) if polyg1.intersects(polyg2): p = polyg1.intersection(polyg2) if (p.area >= polyg1.area * thr_ovlp) or ( p.area >= polyg2.area * thr_ovlp): #if roi_map.has_key(ri): if ri in roi_map: roi_map[ri].append(si) else: roi_map[ri] = [si] si = si + 1 ri = ri + 1 for r in list(roi_map.keys()): if len(roi_map[r]) > 1: roi_map.pop(r, None) roi_map = [(k, roi_map[k][0]) for k in roi_map.keys()] return roi_map
def generate_poly_tiles(poly: Polygon, out): bbox = poly.envelope tiles = {} for z in range(0, 19): tiles[z] = set() tile_xs = [] tile_ys = [] for i in range(0, 4): x = bbox.boundary.xy[0][i] y = bbox.boundary.xy[1][i] tile_x, tile_y = deg2num(y, x, z) tile_xs.append(tile_x) tile_ys.append(tile_y) min_tile_x, min_tile_y = (min(tile_xs), min(tile_ys)) max_tile_x, max_tile_y = (max(tile_xs), max(tile_ys)) for tile_x in range(min_tile_x - 1, max_tile_x + 1): for tile_y in range(min_tile_y - 1, max_tile_y + 1): nw = num2deg(tile_x, tile_y, z) sw = num2deg(tile_x, tile_y + 1, z) ne = num2deg(tile_x + 1, tile_y, z) se = num2deg(tile_x + 1, tile_y + 1, z) box = Polygon([nw, sw, se, sw, nw]) if box.intersects(poly): tiles[z].add((tile_x, tile_y)) for z in tiles: for (x, y) in tiles[z]: out.write('{0} {1} {2}\n'.format(x, y, z)) out.write('0 0 0\n')
def track(self, posx, posy, hollows, obstacles): valid = True copyx = self.posx copyy = self.posy if self.posx > posx: self.posx -= self.body.speed else: self.posx += self.body.speed if self.posy > posy: self.posy -= self.body.speed else: self.posy += self.body.speed coords = [[self.posx, self.posy], [self.posx, self.posy + self.imageHeight], [self.posx + self.imageWidth, self.posy + self.imageHeight], [self.posx, self.posy + self.imageHeight]] enemyRec = Polygon(coords) for o in obstacles: coordsObs = [[o.posx, o.posy], [ o.posx + (o.imageWidth / 3), o.posy ], [o.posx + (o.imageWidth / 3), o.posy + (o.imageHeight / 3)], [o.posx, (o.posy + o.imageHeight / 3)]] polygonO = Polygon(coordsObs) if enemyRec.intersects(polygonO): valid = False if valid: valid = self.verifyPos(copyx, copyy, hollows) if not valid: self.posx -= self.posx - copyx - 2 self.posy -= self.posy - copyy - 2
def get_raw_dirs_groups(self, polygon, dataset, data_bucket, farm, max_results=1): lon_step = self.lon_step lat_step = self.lat_step min_lat_lon = numpy.array(polygon).min(0) max_lat_lon = numpy.array(polygon).max(0) farm_polygon = Polygon(polygon) raw_dirs = {} min_lat_r = int(min_lat_lon[0] / lat_step) * lat_step max_lat_r = int(max_lat_lon[0] / lat_step + 1) * lat_step min_lon_r = int(min_lat_lon[1] / lon_step) * lon_step max_lon_r = int(min_lat_lon[1] / lon_step + 1) * lon_step min_lat_r = round(min_lat_r, 3) max_lat_r = round(max_lat_r, 3) min_lon_r = round(min_lon_r, 3) max_lon_r = round(max_lon_r, 3) last_updated = farm[dataset]['last_updated'] last_updated = datetime.strptime(farm[dataset]['last_updated'], '%Y-%m-%d') for curr_lat in numpy.arange(min_lat_r, max_lat_r, lat_step): for curr_lon in numpy.arange(min_lon_r, max_lon_r, lon_step): curr_lat = round(curr_lat, 3) curr_lon = round(curr_lon, 3) grid_pol = Polygon([[curr_lat, curr_lon], [curr_lat + lat_step, curr_lon], [curr_lat + lat_step, curr_lon + lon_step], [curr_lat, curr_lon + lon_step]]) if grid_pol.intersects(farm_polygon): prefix = 'satellite/raw_satellite_data/' + dataset + '/' + str( curr_lat) + '_' + str(curr_lon) + '/' all_files = list( data_bucket.objects.filter(Prefix=prefix).all()) dates = set() for file in all_files: splited = file.key[len(prefix)::].split('/') if len(splited) > 0: cdate = datetime.strptime(splited[0], '%Y-%m-%d') if last_updated < cdate: dates.add(cdate) for date in dates: if date not in raw_dirs: raw_dirs[date] = [] raw_dirs[date].append((curr_lat, curr_lon)) rel_keys = sorted(raw_dirs.keys())[-max_results::] oraw_dirs = {rk: raw_dirs[rk] for rk in rel_keys} return oraw_dirs
def collide_ln(ln): for poly in POLY_LIST: polygoly = Polygon([list(elem) for elem in poly]) for i in range(0, int(ln.length), 5): ip = ln.interpolate(i) if polygoly.intersects(ip): return True return False
def collide_ln(ln): for poly in POLY_LIST: polygoly = Polygon([list(elem) for elem in poly]) for i in range(0, int(ln.length), 5): ip = ln.interpolate(i) if polygoly.intersects(ip): return True circle(screen, GREEN, [int(ip.x),int(ip.y)], 3, 0) return False
def get_zip(lat, long): zips = search.by_coordinates(lat, long, radius=20, returns=40) print('11370' in [json.loads(i.to_json())['zipcode'] for i in zips]) possiblezips = [] otherzips = [] for azip in zips: azip = json.loads(azip.to_json()) if azip['zipcode'] == '11370': print(len(azip['polygon'])) otherzips.append(azip) if lat < azip['bounds_north'] and lat > azip['bounds_south']: if abs(long) < abs(azip['bounds_west']) and abs(long) > abs( azip['bounds_east']): possiblezips.append(azip) if (len(possiblezips) > 1): for azip in possiblezips: lons_lats_vect = np.column_stack( np.column_stack([tuple(l) for l in azip['polygon'] ])) # Reshape coordinates polygon = Polygon(lons_lats_vect) # create polygon point = Point(long, lat) # create point if polygon.contains(point): otherzips.remove(azip) possiblezips[0] = azip else: if possiblezips[0] in otherzips: otherzips.remove(possiblezips[0]) #check that all of the nearby zip codes are adjacent to the present zip code: p1 = Polygon([tuple(l) for l in possiblezips[0]['polygon']]) finalzips = [] for azip in otherzips: if depth(azip['polygon']) > 2: p2 = Polygon([tuple(l) for l in azip['polygon'][0]]) if azip['zipcode'] == '11370': print(len(azip['polygon'][0])) print("here") else: p2 = Polygon([tuple(l) for l in azip['polygon']]) if azip['zipcode'] == '11370': print("here-") if p1.intersects(p2): finalzips.append(azip) return { "zipCode": possiblezips[0]['zipcode'], "nearbyZipCodes": [i['zipcode'] for i in finalzips], "nearbyCoords": [tuple([i['lat'], i['lng']]) for i in finalzips], "nearbyCountyNames": [i['county'] for i in finalzips], "presentCounty": possiblezips[0]['county'] }
def subset(self, ra_min, ra_max, dec_min, dec_max): poly = Polygon( LinearRing([(ra_min, dec_min), (ra_min, dec_max), (ra_max, dec_max), (ra_max, dec_min)])) mask = np.array([ poly.intersects(self.table['polygon'][i]) for i in range(len(self.table)) ]) log.debug('{} catalogs intersect.'.format(mask.sum())) return VphasCatalogSet(self.table[mask])
def collides(obj): for poly in POLY_LIST: polygoly = Polygon([list(elem) for elem in poly]) if polygoly.intersects(obj): return True inters = polygoly.exterior.intersection(obj) print inters if not inters.is_empty: return True return False
def check_gv_word_in_azure_intersection(gv_info,azure_info): poly_coordinates = [tuple(azure_info["boundingBox"]["p1"]), (azure_info["boundingBox"]["p3"][0],azure_info["boundingBox"]["p1"][1]), tuple(azure_info["boundingBox"]["p3"]), (azure_info["boundingBox"]["p1"][0],azure_info["boundingBox"]["p3"][1])] point_coordinates = [gv_info[i:i + 2] for i in range(0, len(gv_info), 2)] point = Polygon(point_coordinates) polygon = Polygon(poly_coordinates) # print(polygon.contains(point)) return polygon.intersects(point)
def compare_tile_segment(coordinates, tile, image_dir, tile_images_directory): """ Compares whether the box bounded by the tile's original coordinates intersects the tumor segment indicated in the xml file. Saves all tiles images. Arguments: coordinates: a list of tumor segments coordinates from xml annotations tile: the tile being investigated image_dir: directory of original WSI files tile_images_directory: directory to which images of tiles will be saved Returns: Depending on the positivity of the tile: - if positive tumor: returns the coordinates on that tile image of the tumor region(s) - if negative: returns None, None values """ box = Box(tile.o_c_s, tile.o_r_s, tile.o_c_e, tile.o_r_e) for i in range(len(coordinates)): # We disregard coordinates with less than 2 xy values if len(coordinates[i]) < 3: continue if not os.path.exists(tile_images_directory + tile.file_title + "_" + str(tile.tile_num) + '.png'): save_tile_image(tile, image_dir, tile_images_directory) print(tile.file_title + "_", str(tile.tile_num) + ".png image saved") segment = Polygon(coordinates[i]) if segment.intersects(box): segment = transform(reflection(1), segment) box = transform(reflection(1), box) try: overlap = segment.intersection(box) except: print("Error in ", tile.file_title, " num: ", tile.tile_num, " coord index: ", i) continue if isinstance(overlap, MultiPolygon): x_overlap_shifted_list = [] y_overlap_shifted_list = [] for element in overlap: x_overlap_shifted, y_overlap_shifted = get_xy(tile, element) x_overlap_shifted_list.append(x_overlap_shifted) y_overlap_shifted_list.append(y_overlap_shifted) return x_overlap_shifted_list, y_overlap_shifted_list else: x_overlap_shifted, y_overlap_shifted = get_xy(tile, overlap) return x_overlap_shifted, y_overlap_shifted else: continue return None, None
def validatePosition(curr, size, existing): img_box = Polygon([tuple(curr), (curr[0] + size[0], curr[1]), (curr[0] + size[0], curr[1] + size[1]), (curr[0], curr[1] + size[1])]) flag = True for region in existing: poly = Polygon(region) if poly.intersects(img_box): flag = False break return flag
def verifier(self, displayWidth, displayHeight): # Verifica que los agujeros no se superpongan quantity = self.map.hollowsN if quantity == 2: h1 = self.map.hollows[0] h2 = self.map.hollows[1] polygon1 = Polygon(h1.corners) polygon2 = Polygon(h2.corners) if polygon1.intersects(polygon2): print('No verificado') self.build_hollows(displayWidth, displayHeight)
def subset(self, ra_min, ra_max, dec_min, dec_max): poly = Polygon(LinearRing([(ra_min, dec_min), (ra_min, dec_max), (ra_max, dec_max), (ra_max, dec_min)])) mask = np.array( [poly.intersects(self.table['polygon'][i]) for i in range(len(self.table))] ) log.debug('{} catalogs intersect.'.format(mask.sum())) return VphasCatalogSet(self.table[mask])
def attack(self, enemies, coords, coords2): playerRec = Polygon(coords2) for e in enemies: if e.room == self.room: coords = [ [e.posx, e.posy], [e.posx, e.posy + e.imageHeight], [e.posx + e.imageWidth, e.posy + e.imageHeight], [e.posx, e.posy + e.imageHeight] ] polygonE = Polygon(coords) if polygonE.intersects(playerRec): e.body.defaultLife -= self.damageV return enemies
def isThereNoCollisions(points, wholeMap): p1 = Polygon(points) x0, y0 = points[0] for collisionsIndex in range(collisionsLen): collision = collisions[collisionsIndex] x1, y1 = collision[0] if wholeMap and (x1 - x0)**2 + ( y1 - y0)**2 > 625: # 15 * 15 = 225 # 25 *25 = 625 continue p2 = Polygon(collision) if p1.intersects(p2): return False return True
def attack(self, coords2, room, life): playerRecFeets = Polygon(coords2) if self.room == room: coords = [[self.posx, self.posy], [self.posx, self.posy + self.imageHeight], [ self.posx + self.imageWidth, self.posy + self.imageHeight ], [self.posx, self.posy + self.imageHeight]] polygonE = Polygon(coords) if polygonE.intersects(playerRecFeets): life -= self.body.damage return life
def get_natura_table(min_lat, min_lon, max_lat, max_lon): import os from shapely.geometry.polygon import Polygon natura_table = [] min_grid_lat = '' min_grid_lon = '' resolution = '' grid_tables = [] grid_lat_lon_min_max_list = [] grid_files_list = [] for filename in os.listdir( 'visualizer/static/visualizer/natura_grid_files'): if filename.endswith("info"): with open( 'visualizer/static/visualizer/natura_grid_files/' + str(filename), 'r') as file: natura_info = json.load(file) min_grid_lat = natura_info['min_lat'] min_grid_lon = natura_info['min_lon'] max_grid_lat = natura_info['max_lat'] max_grid_lon = natura_info['max_lon'] grid_polygon = Polygon([(max_grid_lat, min_grid_lon), (min_grid_lat, min_grid_lon), (min_grid_lat, max_grid_lon), (max_grid_lat, max_grid_lon)]) spill_polygon = Polygon([(max_lat, min_lon), (min_lat, min_lon), (min_lat, max_lon), (max_lat, max_lon)]) if grid_polygon.intersects(spill_polygon): grid_files_list.append(filename) grid_lat_lon_min_max_list.append(natura_info) print 'Intersection of spill area with grid areas' for grid_file in grid_files_list: import sys if sys.argv[1] == 'runserver': with open( 'visualizer/static/visualizer/natura_grid_files/' + str(grid_file).split('__')[0] + '_.csv', 'r') as csvfile: reader = csv.reader(csvfile) natura_table = [[int(e) for e in r] for r in reader] csvfile.close() else: import pyarrow.parquet as pq natura_table = pq.read_table( 'visualizer/static/visualizer/natura_grid_files/' + str(grid_file).split('__')[0] + '_.parquet') grid_tables.append(natura_table) print 'Creation of grid tables' return grid_tables, grid_lat_lon_min_max_list
def compare_poly(p1, p2, p1_, p2_): poly1 = Polygon([p1, (p1[0], p2[1]), p2, (p2[0], p1[1])]) poly2 = Polygon([p1_, (p1_[0], p2_[1]), p2_, (p2_[0], p1_[1])]) if poly1.intersects(poly2): PT1 = Point(p1) PT2 = Point(p2) PT1_ = Point(p1_) PT2_ = Point(p2_) if poly1.contains(PT1_) and poly1.contains(PT2_): return True elif poly2.contains(PT1) and poly2.contains(PT2): return True elif poly1.contains(PT1_): ul = (p1_[0], p1_[1]) lr = (p2[0], p2[1]) area1 = poly1.area area2 = poly2.area area = (lr[0] - ul[0]) * (ul[1] - lr[1]) if float(area) / float(area1) >= 0.5 and float(area) / float( area2) >= 0.5: return True elif poly2.contains(PT1_): ul = (p1[0], p1[1]) lr = (p2_[0], p2_[1]) area1 = poly1.area area2 = poly2.area area = (lr[0] - ul[0]) * (ul[1] - lr[1]) if float(area) / float(area1) >= 0.5 and float(area) / float( area2) >= 0.5: return True elif p1[0] > p1_[0]: ur = (p2_[0], p1_[1]) ll = (p1[0], p2[1]) area1 = poly1.area area2 = poly2.area area = (ur[0] - ll[0]) * (ur[1] - ll[1]) if float(area) / float(area1) >= 0.5 and float(area) / float( area2) >= 0.5: return True elif p1_[0] > p1[0]: ur = (p2[0], p1[1]) ll = (p1_[0], p2_[1]) area1 = poly1.area area2 = poly2.area area = (ur[0] - ll[0]) * (ur[1] - ll[1]) if float(area) / float(area1) >= 0.5 and float(area) / float( area2) >= 0.5: return True return False
def is_intersecting(object, polygon): p1 = Pn([(o.x, o.y) for o in polygon.list_points]) obj_half_width = object.width / 2 obj_half_height = object.height / 2 top_left = (object.x_center - obj_half_width, object.y_center - obj_half_height) bottom_right = (object.x_center + obj_half_width, object.y_center + obj_half_height) top_right = (object.x_center + obj_half_width, object.y_center - obj_half_height) bottom_left = (object.x_center - obj_half_width, object.y_center + obj_half_height) p2 = Pn([top_left, top_right, bottom_left, bottom_right]) return p1.intersects(p2)
def checkbb(bbs, ps, secs, lsfornextlevel): if len(secs) == 0: return {} thisbb = bbs.pop() thisp = ps.pop() thissec = secs.pop() thisl = lsfornextlevel.pop() new_lfornextlevel = [] if len(thisl) == 0: return checkbb(bbs.copy(), ps.copy(), secs.copy(), lsfornextlevel.copy()) # i denotes the chosen discrete prior; i = thisl[np.random.randint(len(thisl))] prior1 = thisp[i] bb1 = rotate_bb_local_np(thisbb, prior1[3]) + prior1[[0, 2]] polygon1 = Polygon(bb1).buffer(.15) """ # bb visualization; fig,ax = plt.subplots(1) rect = patches.Polygon(bb1,True,alpha=0.4) vis_patches.append(rect) vp = PatchCollection(vis_patches, alpha=0.4) ax.add_collection(vp) # ax.add_patch(rect) plt.plot(thisp[:, 0], thisp[:, 2], 'ro', alpha=0.4) plt.show() """ for (bb, p, sec, l) in zip(bbs, ps, secs, lsfornextlevel): # check all other discrete priors; new_l = [] for j in l: if j == i: continue prior2 = np.array(p[j]) bb2 = rotate_bb_local_np(bb, prior2[3]) + prior2[[0, 2]] polygon2 = Polygon(bb2).buffer(.05) if not polygon1.intersects(polygon2) or tier[sec] != tier[thissec]: new_l.append(j) new_lfornextlevel.append(new_l) # recursively add the following discrete priors; pendinglist = checkbb(bbs.copy(), ps.copy(), secs.copy(), new_lfornextlevel) if thissec not in pendinglist: pendinglist[thissec] = [i] else: pendinglist[thissec].append(i) return pendinglist
def __GetZipFromGPS(self, lon, lat): ZipCodeResult = None x = int((lon - float(self.ZipGridDict['Meta']['lon_min'])) * self.ZipGridDict['Meta']['lon_scale']) y = int((lat - float(self.ZipGridDict['Meta']['lat_min'])) * self.ZipGridDict['Meta']['lat_scale']) if ((x >= 0 and x < self.ZipGridDict['Meta']['lon_fields']) and (y >= 0 and y < self.ZipGridDict['Meta']['lat_fields'])): NodeLocation = Point(lon, lat) FieldIndex = str(y * self.ZipGridDict['Meta']['lon_fields'] + x) for ZipCode in self.ZipGridDict['Fields'][FieldIndex]: ZipFileName = self.ZipAreaDict[ZipCode]['FileName'] ZipAreaJson = None with open(ZipFileName, "r") as fp: ZipAreaJson = json.load(fp) if "geometries" in ZipAreaJson: TrackBase = ZipAreaJson["geometries"][0]["coordinates"] elif "coordinates" in ZipAreaJson: TrackBase = ZipJson["coordinates"] else: TrackBase = None print('Problem parsing %s' % ZipFileName) continue AreaMatch = 0 for Track in TrackBase: Shape = [] for t in Track[0]: Shape.append((t[0], t[1])) ZipPolygon = Polygon(Shape) if ZipPolygon.intersects(NodeLocation): AreaMatch += 1 if AreaMatch == 1: ZipCodeResult = ZipCode break return ZipCodeResult
def find_skiarea(slopeCoords, point, slope, skiarea): slopeCoords = toArray(slopeCoords) nearest = None areaNearest = [] valNearest = 1000000000 area2 = [] for areas in skiarea: for area in areas["GeoShape"]["GeoCoordinate"]: name = (areas["name"] if "name" in areas else "-") shape = np.array(area).shape # print(str(shape) + "\t"+ name) area2 = area if len(shape) != 1: area2 = area[0] for i in range(1, len(area)): area2.extend(area[i]) mean = get_mean(area2) if valNearest > np.linalg.norm(mean - np.array(point)): nearest = name areaNearest = toArray(area2) valNearest = np.linalg.norm(mean - np.array(point)) found = False if len(slopeCoords) > 2: p1 = Polygon(slopeCoords) p2 = Polygon(areaNearest) found = p1.intersects(p2) elif len(slopeCoords) == 2: p1 = LineString(slopeCoords) p2 = Polygon(areaNearest) found = p1.intersects(p2) if nearest != None and nearest != "-" and found: slope["skiarea"] = nearest newDataset["records"].append(slope) return True newDataset["records"].append(slope) return False
def overlapsScene(self, extent, bbox): """ Placeholder """ # create scene extent polygon p1 = Polygon([(extent['ulx'], extent['uly']), (extent['lrx'], extent['uly']), (extent['lrx'], extent['lry']), (extent['ulx'], extent['lry']), (extent['ulx'], extent['uly'])]) # create aoi polygon p2 = Polygon([(bbox['ulx'], bbox['uly']), (bbox['lrx'], bbox['uly']), (bbox['lrx'], bbox['lry']), (bbox['ulx'], bbox['lry']), (bbox['ulx'], bbox['uly'])]) return p1.intersects(p2)
def check_vicinity(gv_bb,bb): point_coordinates = [gv_bb[i:i + 2] for i in range(0, len(gv_bb), 2)] polygon_gv = Polygon(point_coordinates) p1 = bb[:2][0]-5 , bb[:2][1]-5 p2 = bb[2:4][0]+5 , bb[2:4][1]-5 p3 = bb[4:6][0]+5 , bb[4:6][1]+5 p4 = bb[6:][0]-5 , bb[6:][1]+5 poly_coordinates = [p1,p2,p3,p4] polygon_az = Polygon(poly_coordinates) # print(polygon.contains(point)) return polygon_gv.intersects(polygon_az)
def ugrid_area(): # path = '/home/benkoziol/htmp/src_subset_1.nc' path = '/home/benkoziol/l/data/ocgis/ugrid-cesm-subsetting/UGRID_1km-merge-10min_HYDRO1K-merge-nomask_c130402.nc' rd = RequestDataset(path) vc = rd.get_raw_field() vc.load() face_nodes = vc['landmesh_face_node'].get_value() face_node_x = vc['landmesh_node_x'].get_value() face_node_y = vc['landmesh_node_y'].get_value() face_center_x = vc['landmesh_face_x'].get_value() face_center_y = vc['landmesh_face_y'].get_value() areas = [] for ctr, idx in enumerate(range(face_nodes.shape[0])): if ctr % 10000 == 0: print '{} of {}'.format(ctr, face_nodes.shape[0]) curr_face_indices = face_nodes[idx, :] curr_face_node_x = face_node_x[curr_face_indices] curr_face_node_y = face_node_y[curr_face_indices] face_coords = np.zeros((4, 2)) face_coords[:, 0] = curr_face_node_x face_coords[:, 1] = curr_face_node_y poly = Polygon(face_coords) parea = poly.area poly = shapely.geometry.box(*poly.bounds) pt = Point(face_center_x[idx], face_center_y[idx]) if not poly.intersects(pt): print idx, np.array(pt), poly.bounds # if parea > 1: # print idx # print face_nodes[idx, :] # print face_coords # print poly.bounds # sys.exit() areas.append(parea)
def __init__(self, axis_resolution, orientation_resolution, average_path_length, vehicle_length, x_variance, y_variance, orientation_variance, obstacles=None, ): ''' resolution is integers representing the cardinality of the dimensions. For exaple, axis_resolution=4 would create a 4x4 grid. average_path_length is the average length of a path taken for the transition probability. ''' self.axis_resolution = axis_resolution self.orientation_resolution = orientation_resolution self.average_path_length = average_path_length self.vehicle_length = vehicle_length self.x_variance = x_variance self.y_variance = y_variance self.orientation_variance = orientation_variance self.orientation_tolerance = ANGLE_MOD * 1.0 / orientation_resolution is_bad = [[False] * axis_resolution for _ in range(axis_resolution)] if obstacles: for r, c in itertools.product(range(axis_resolution), range(axis_resolution)): (x1, x2), (y1, y2), (_, _) = self.StateToCoorRange((r, c, 0)) # CCW square = Polygon([(x2, y2), (x1, y2), (x1, y1), (x2, y1)]) if square.intersects(obstacles) or obstacles.contains(square): is_bad[r][c] = True self.is_bad = is_bad
def categorizeBuildings(self): def isLeft(a,b,c): return ((b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0])) > 0; def getIntersectionArea(bldPoly,line,perpLine,bldID): if not line.intersects(bldPoly): return 0.0 pt1 = list(line.coords)[0] pt2 = list(line.coords)[1] perppt1 = list(perpLine.coords)[0] perppt2 = list(perpLine.coords)[1] dx = perppt2[0] - perppt1[0] dy = perppt2[1] - perppt1[1] pt3 = (pt1[0]-dx,pt1[1]-dy) pt4 = (pt2[0]-dx,pt2[1]-dy) linePoly = Polygon([pt1,pt3,pt4,pt2]) try: intersection_area = linePoly.intersection(bldPoly).area return intersection_area/bldPoly.area except: return -1 def overlapsNeighbor(bldPoly,neighborPoly): try: intersection_area = bldPoly.intersection(neighborPoly).area return intersection_area/bldPoly.area > 0.05 except: return False Rd2BldLeft = {} Rd2BldRight = {} for bld in self.buildingCenters.keys(): bldID = self.buildingCenters[bld][0] #if bldID < 3700 or bldID > 3800: #if bldID != 3751: #continue roads = self.segment_lookup([bld[0],bld[1]],10) p1 = (bld[0], bld[1]) p1LatLon = to_latlon(p1) res = self.buildingKDTree.query([bld[0],bld[1]], 20) neighbors = [] for item in res[1][1:]: #start from index 1 because index 0 is always the original building bld buildingID = self.buildingCenters[self.buildingCenters.keys()[item]][0] neighbor = self.buildings[buildingID] #this part removes a bug that some neighbor shapes have extra information, which will result in Polygon error later on. start = neighbor[0] for i in range(1,len(neighbor)): if neighbor[i] == start and i > 2: break neighbor = neighbor[:i+1] neighbors.append(neighbor) roadDict = {} bldVertices = self.buildingCenters[bld][1] bldPolygon = Polygon(bldVertices) for rd in roads: rdLine = LineString([rd[0],rd[1]]) intersectsSomething = False p3Intersect = self.perpIntersectPoint(p1,rd[0],rd[1]) if not p3Intersect: continue bldVertices.append(p1) for vertex in bldVertices: if intersectsSomething: break p3 = self.perpIntersectPoint(vertex,rd[0],rd[1]) vertexLatLon = to_latlon(vertex) if p3: p3LatLon = to_latlon(p3) perpLine = LineString([p1,p3]) for neighbor in neighbors: neighborPoly = Polygon(neighbor) if overlapsNeighbor(bldPolygon,neighborPoly): continue if perpLine.intersects(neighborPoly): intersectRd = False intersectionRdArea = 0 if neighborPoly.intersects(rdLine): intersectRd = True intersectionRdArea = getIntersectionArea(neighborPoly,rdLine,perpLine,bldID) if intersectionRdArea > 0.4 or not intersectRd: #if bldID == 4287 or bldID == 4288: #print intersectionRdArea #road_lines.record(0) #road_lines.poly(shapeType=shapefile.POLYLINE, parts=[[vertexLatLon,p3LatLon]]) intersectsSomething = True break for rd2 in roads: if rd2 == rd: continue roadLine2 = LineString([rd2[0],rd2[1]]) if perpLine.intersects(roadLine2): intersectsSomething = True break if not intersectsSomething: perpLine = LineString([p1,p3Intersect]) if perpLine.length > (3*bldPolygon.length)/4: continue #if rdLine.length < (bldPolygon.length/3): # continue p3IntersectLatLon = to_latlon(p3Intersect) road_lines.record(0) road_lines.poly(shapeType=shapefile.POLYLINE, parts=[[p3IntersectLatLon,p1LatLon]]) if isLeft(rd[0],rd[1],p1): if rd not in Rd2BldLeft: Rd2BldLeft[rd] = [bldID] else: Rd2BldLeft[rd].append(bldID) else: if rd not in Rd2BldRight: Rd2BldRight[rd] = [bldID] else: Rd2BldRight[rd].append(bldID) return (Rd2BldLeft, Rd2BldRight)