def zipFans(location): retVal = {} zipCodes = loadBaseMap('zipcodes') for feature in zipCodes['features']: s = shape(feature['geometry']) try: polygon = SPolygon(s) except: polygon = MPolygon(s) zip = feature['properties']['zip'] if (location.within(polygon)): location = polygon.centroid ncaaf_favs = loadFansZip('ncaaf') mlb_favs = loadFansZip('mlb') try: retVal['ncaaf'] = ncaaf_favs[zip] except: pass try: retVal['mlb'] = mlb_favs[zip] except: pass return (retVal, location)
def chain_filter_polygon(request, queryset): """Filter queryset by polygon borders. This filter is FINAL, must be used as last. """ print('final') if not request.GET.get('polygon'): return queryset polygon = None try: polygon = Polygon.objects.get(pk=request.GET.get('polygon')) except Polygon.DoesNotExist: raise TreeFilterException('Polygon not found.', status.HTTP_404_NOT_FOUND) borders = obtain_polygon_borders(polygon) trees = queryset.filter(latitude__lte=borders['lat_max'], latitude__gte=borders['lat_min'], longitude__lte=borders['lng_max'], longitude__gte=borders['lng_min']) # filter trees to match polygon. filter_poly = SPolygon([(p.latitude, p.longitude) for p in polygon.points.all()]) def filter_func(tree): """Inner function to filter tree by geo coordinates.""" return filter_poly.intersects(SPoint(tree.latitude, tree.longitude)) return filter(filter_func, trees)
def coverage(obj: Collection) -> Union[SPolygon, SPoint, GeometryCollection]: """Create a shapely object. Used to calculate area/coverage. Args: obj: One or more shapes. Returns: A shapely object representing the union of coverage for all input shapes. """ if type(obj) is list: cover = coverage(obj[0]) for o in obj[1:]: cover = cover.union(coverage(o)) return cover elif type(obj) in [Polygon, Spline, Line]: return SPolygon([pt.state() for pt in obj.points]) elif type(obj) is Circle: c = obj.c.state() return SPoint(c[0], c[1]).buffer(obj.r.state()) else: print("Can't get coverage for:", obj)
def draw_clusters(draw, clusters, pattern): for cluster in clusters: color = pattern.colors[cluster[0].color_index] polygons = [ SPolygon([(v.x, v.y) for v in p.list_vertices]) for p in cluster ] path = cascaded_union(polygons).buffer(0) draw_path(draw, path, color)
def polygon_area(vertices: Sequence[Pnt]) -> float: """Find the area of a polygon. Args: vertices: The vertex points. Returns: The area. """ return SPolygon(vertices).area
def convert(self): l = [] l.extend(self.indices) l.append(len(self.points)) p = [] for i, j in zip(l, l[1:]): spoints = [(point.x, point.y) for point in self.points[i:j - 1]] p.append(spoints) shell = p[0] holes = p[1:] return SPolygon(shell=shell, holes=holes)
def centroid(shape: Shape) -> Pnt: """Find the centroid of a shape. Args: shape: A shape. Returns: A point. """ if type(shape) in [Polygon, Spline, Line]: return SPolygon([p.state() for p in shape.points]).centroid.coords[0] elif type(shape) is Circle: return shape.c
def ExtractInlandZones(doc): placemarks = list(doc.Document.Folder.Placemark) zones = {} for pm in placemarks: name = pm.name.text # The Pinon Canyon Maneuver Site location appears to be included # in error, and looks like the basis for one of the 3km areas of Fort # Carson. if name == 'Pinon Canyon Maneuver Site': continue # Naming for Aberdeen Proving Ground has some inconsistencies. # Normalize to a single name. if name.find('Aberdeen') != -1: name = 'Aberdeen Proving Ground Military Reservation' # TODO: make a more general KML->Shapely converter or import one # from somewhere. polygons = list(pm.MultiGeometry.Polygon) print 'Found zone %s with %d polygons' % (name, len(polygons)) for poly in polygons: coordinates = poly.outerBoundaryIs.LinearRing.coordinates.text coords = coordinates.split(' ') latLng = [] holeLatLngs = [] for c in coords: if c.strip(): xy = c.strip().split(',') latLng.append([float(xy[0]), float(xy[1])]) if poly.find('{http://www.opengis.net/kml/2.2}innerBoundaryIs'): holes = list(poly.innerBoundaryIs) for h in holes: holeCoordinates = h.LinearRing.coordinates.text holeCoords = holeCoordinates.split(' ') holeLatLng = [] for c in holeCoords: if c.strip(): xy = c.strip().split(',') holeLatLng.append([float(xy[0]), float(xy[1])]) holeLatLngs.append(holeLatLng) spolygon = SPolygon(latLng, holeLatLngs) if not spolygon.is_valid: raise Exception('Invalid polygon for %s' % name) if not name in zones: zones[name] = [] print 'Got polygon (%f) for %s' % (spolygon.area, name) zones[name].append(spolygon) return zones
def metroFans(location, returnDict): metros = loadBaseMap('metros') for feature in metros['features']: s = shape(feature['geometry']) try: polygon = SPolygon(s) except: polygon = MPolygon(s) area_name = feature['geometry']['properties']['name'] if(area_name == 'New York NY'): print polygon if (polygon.contains(location) or polygon.touches(location)): nba_favs = loadFansMetro('nba') nfl_favs = loadFansMetro('nfl') nhl_favs = loadFansMetro('nhl') try: returnDict['nba'] = nba_favs[area_name] except: print 'error nba' try: returnDict['nfl'] = nfl_favs[area_name] except: print 'error nfl' try: returnDict['nhl'] = nhl_favs[area_name] except: print 'error nhl' return returnDict
def sample_points_in_shape(shape: dict, n: int) -> List[Pnt]: """Sample random points inside a shape. Args: shape: A shape (currently works for polygons and splines). n: Number of points to sample. Returns: The sampled points. """ bound = bounding_box(shape) points = [] for i in range(n): while True: p = ( np.random.uniform(bound[0], bound[2]), np.random.uniform(bound[1], bound[3]), ) region = SPolygon([pt.state() for pt in shape.points]) if SPoint(p[0], p[1]).within(region): points.append(p) break return points
def ConvertShapeToPlacemark(shape, geoid, aland, awater, kml): #if len(shape.parts) > 1: # print '----------geoid=%s aland=%s awater=%s' % (geoid, aland, awater) if shape.shapeType != 5: raise Exception('Unexpected shape type [%d] in file' % shape.shapeType) pm = KML.Placemark( KML.name('%s' % geoid), KML.styleUrl('#ts'), KML.ExtendedData( KML.Data( KML.displayName('ALAND'), KML.value(aland), name='string' ), KML.Data( KML.displayName('AWATER'), KML.value(awater), name='string' ) ), KML.MultiGeometry( KML.Polygon( KML.extrude(0), KML.altitudeMode('clampToGround') ) ) ) # The parentPoly will be used to append rings, and a # new Polygon will be appended for multiple rings in # a geography. parentPoly = pm.MultiGeometry.Polygon #if len(shape.parts) > 1: # print 'shape has %d parts' % len(shape.parts) for i in range(0, len(shape.parts)): lo = shape.parts[i] hi = len(shape.points) if i < len(shape.parts) - 1: hi = shape.parts[i + 1] #if len(shape.parts) > 1: # print 'shape has points in [%d, %d) of %d' % (lo, hi, len(shape.points)) if (shape.points[lo][0] != shape.points[hi-1][0] or shape.points[lo][1] != shape.points[hi-1][1]): raise Exception('Loop endpoints in [%d, %d) do not match' % (lo, hi)) coords = [] for j in reversed(range(lo, hi)): lng = shape.points[j][0] lat = shape.points[j][1] coords.append([lng, lat]) latlngCoords = [] for c in coords: latlngCoords.append('%f,%f,0' % (c[0], c[1])) coordinates = ' '.join(latlngCoords) # Note: need LinearRing to compute ccw. Need Polygon to compute contains(). spoly = SPolygon(coords) if i == 0: parentSpoly = spoly ring = polygon.LinearRing(coords) # Some sanity checks to make sure all rings are closed, non-empty, # and valid. if not ring.is_ring: raise Exception('Badly formatted non-ring : %s' % geoid) if ring.is_empty: raise Exception('Empty geometry found: %s' % geoid) if not ring.is_valid: raise Exception('Invalid ring: %s' % geoid) if not ring.is_ccw: # This ring is an internal (enclave) ring. rring = copy.deepcopy(ring) rring.coords = list(rring.coords)[::-1] # Shapely contains does not handle point-overlaps. This # means that enclaves which touch the containing ring # are not handled correctly. To cure this, we check two # points. if not (parentSpoly.contains(SPoint(rring.coords[0])) or parentSpoly.contains(SPoint(rring.coords[1]))): print 'Out-of-order enclave' # print 'ring %s does not contain %s' % (parentSpoly, ring) # print ring # print rring # Note: if this triggers, we will need to store the polys # to figure out which one is the enclosing one. Hopefully # the census files will not exhibit this, although it is # legal strictly according to the shapefule spec. raise Exception('Out-of-order enclave') coordinates = coordinates + ' 0,0,0' parentPoly.append(KML.innerBoundaryIs( KML.LinearRing( KML.coordinates(coordinates) ) )) else: # Find the containing poly... parentPoly.append(KML.innerBoundaryIs( KML.LinearRing( KML.coordinates(coordinates) ) )) else: if i > 0: # Set the new parent polygon ring. parentSpoly = spoly parentPoly = KML.Polygon( KML.extrude(0), KML.altitudeMode('clampToGround')) pm.MultiGeometry.append(parentPoly) parentPoly.append(KML.outerBoundaryIs( KML.LinearRing( KML.coordinates(coordinates) ) )) return pm
def plot_state(directions_list, trim_names=True): """ Plots the facets of a run """ global midRA, midDec, fig, at, selected_direction selected_direction = None # Set up coordinate system and figure points, midRA, midDec = factor.directions.getxy(directions_list) fig = plt.figure(1, figsize=(10, 9)) if hasWCSaxes: wcs = factor.directions.makeWCS(midRA, midDec) ax = WCSAxes(fig, [0.16, 0.1, 0.8, 0.8], wcs=wcs) fig.add_axes(ax) else: ax = plt.gca() field_x = min(points[0]) field_y = max(points[1]) adjust_xy = True while adjust_xy: adjust_xy = False for xy in points: dist = np.sqrt((xy[0] - field_x)**2 + (xy[1] - field_y)**2) if dist < 10.0: field_x -= 1 field_y += 1 adjust_xy = True break field_ra, field_dec = factor.directions.xy2radec([field_x], [field_y], refRA=midRA, refDec=midDec) field = Direction('field', field_ra[0], field_dec[0], factor_working_dir=directions_list[0].working_dir) directions_list.append(field) ax.set_title('Overview of FACTOR run in\n{}'.format( directions_list[0].working_dir)) # Plot facets markers = [] for direction in directions_list: if direction.name != 'field': vertices = read_vertices(direction.vertices_file) RAverts = vertices[0] Decverts = vertices[1] xverts, yverts = factor.directions.radec2xy(RAverts, Decverts, refRA=midRA, refDec=midDec) xyverts = [np.array([xp, yp]) for xp, yp in zip(xverts, yverts)] mpl_poly = Polygon(np.array(xyverts), edgecolor='#a9a9a9', facecolor='#F2F2F2', clip_box=ax.bbox, picker=3.0, linewidth=2) else: xverts = [field_x] yverts = [field_y] mpl_poly = Circle((field_x, field_y), radius=5.0, edgecolor='#a9a9a9', facecolor='#F2F2F2', clip_box=ax.bbox, picker=3.0, linewidth=2) mpl_poly.facet_name = direction.name mpl_poly.completed_ops = get_completed_ops(direction) mpl_poly.started_ops = get_started_ops(direction) mpl_poly.current_op = get_current_op(direction) set_patch_color(mpl_poly, direction) ax.add_patch(mpl_poly) # Add facet names if direction.name != 'field': poly_tuple = tuple([(xp, yp) for xp, yp in zip(xverts, yverts)]) xmid = SPolygon(poly_tuple).centroid.x ymid = SPolygon(poly_tuple).centroid.y else: xmid = field_x ymid = field_y if trim_names: name = direction.name.split('_')[-1] else: name = direction.name marker = ax.text(xmid, ymid, name, color='k', clip_on=True, clip_box=ax.bbox, ha='center', va='bottom') marker.set_zorder(1001) markers.append(marker) # Add info box at = AnchoredText("Selected direction: None", prop=dict(size=12), frameon=True, loc=3) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") at.set_zorder(1002) ax.add_artist(at) ax.relim() ax.autoscale() ax.set_aspect('equal') if hasWCSaxes: RAAxis = ax.coords['ra'] RAAxis.set_axislabel('RA', minpad=0.75) RAAxis.set_major_formatter('hh:mm:ss') DecAxis = ax.coords['dec'] DecAxis.set_axislabel('Dec', minpad=0.75) DecAxis.set_major_formatter('dd:mm:ss') ax.coords.grid(color='black', alpha=0.5, linestyle='solid') else: plt.xlabel("RA (arb. units)") plt.ylabel("Dec (arb. units)") # Define coodinate formater to show RA and Dec under mouse pointer ax.format_coord = formatCoord # Show legend not_processed_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F2F2F2', linewidth=2) processing_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F2F5A9', linewidth=2) selfcal_ok_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#A9F5A9', linewidth=2) selfcal_not_ok_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F5A9A9', linewidth=2) l = ax.legend([ not_processed_patch, processing_patch, selfcal_ok_patch, selfcal_not_ok_patch ], ['Unprocessed', 'Processing', 'Completed', 'Failed']) l.set_zorder(1002) # Add check for mouse clicks and key presses fig.canvas.mpl_connect('pick_event', on_pick) fig.canvas.mpl_connect('key_press_event', on_press) # Add timer to update the plot every 60 seconds timer = fig.canvas.new_timer(interval=60000) timer.add_callback(update_plot) timer.start() # Show plot plt.show() plt.close(fig) # Clean up any temp pyrap images if os.path.exists('/tmp/tempimage'): shutil.rmtree('/tmp/tempimage')
def translate_points(pts, xoff, yoff): poly = SPolygon(pts) poly = affinity.translate(poly, xoff, yoff) return list(poly.exterior.coords)
def scale_points(pts, xscale, yscale): poly = SPolygon(pts) poly = affinity.scale(poly, xscale, yscale) return list(poly.exterior.coords)
def rotate_points(pts, rad): poly = SPolygon(pts) poly = affinity.rotate(poly, rad, origin="centroid", use_radians=True) pts = array(list(poly.exterior.coords)) return pts[:-1]
plow = [-58, latLng[-1][1]] latLng.append(plow) latLng.append(phigh) print 'Append %s' % plow print 'Append %s' % phigh if name == 'West Combined Contour': phigh = [-126, latLng[0][1]] print 'Prepend %s' % phigh latLng.insert(0, phigh) plow = [-126, latLng[-1][1]] latLng.append(plow) latLng.append(phigh) print 'Append %s' % plow print 'Append %s' % phigh conusArea = SPolygon(conusBorder) area = SPolygon(latLng) zix = area.intersection(conusArea) zones[name] = [zix] # Create the KML document skeleton doc = KML.kml( KML.Document( KML.name('Protection Zones'), KML.Style(KML.LineStyle(KML.color('ff0000ff'), KML.width(2)), KML.PolyStyle(KML.color('66000066')), id="stl"), KML.Style(KML.LineStyle(KML.color('ff00ffff'), KML.width(4)), KML.PolyStyle(KML.color('00006666')), id="stlx"), KML.Style(KML.LineStyle(KML.color('ff00ff00'), KML.width(2)),