def convert_multi_polygon(self, coverage_areas): try: multi_polygon = list() for coverage_area in coverage_areas: multi_polygon.append([self.format_polygon(coverage_area)]) coordinates_multi_polygon = MultiPolygon(multi_polygon) return coordinates_multi_polygon except: return MultiPolygon([[[3.78, 9.28], [-130.91, 1.52]]]) # multi_polygon invalid
def partner_create(request): """ validate input json, clean xss entry, insert document on db :param request: json :return: """ invalid, reason = input_validator_module.validate_keys(request, [ 'id', 'tradingName', 'ownerName', 'document', 'coverageArea', 'address' ], {"id": int}, required=True) if invalid: return formatting_module.output_format(reason), 415 partner_id = sanitize_input_module.entry_clean(request.json['id']) trading_name = sanitize_input_module.entry_clean( request.json['tradingName']) owner_name = sanitize_input_module.entry_clean(request.json['ownerName']) document = sanitize_input_module.entry_clean(request.json['document']) coverage_area = request.json['coverageArea'] address = request.json['address'] partner = { "id": partner_id, "trading_name": trading_name, "owner_name": owner_name, "document": document, "coverageArea": MultiPolygon(coverage_area['coordinates']), "address": Point(address['coordinates']) } partner = Partner(partner) output, code = partner.partner_create() return formatting_module.output_format(output), code
def json2geojson(data): mileuzones = data["milieuzones"] features = [] for element in mileuzones: if "milieuzone" in element: milieuzone = element["milieuzone"] multipolygon = None geo = loads(milieuzone["geo"]) # Extract multipolygon if type(geo) is MultiPolygon: multipolygon = geo elif type(geo) is GeometryCollection: for f in geo["geometries"]: if type(f) is Polygon: multipolygon = MultiPolygon(f) break elif type(f) is MultiPolygon: multipolygon = f break if multipolygon is None: raise Exception("Missing (multi)polygon") properties = { key: milieuzone[key] for key in ("id", "verkeerstype", "vanafdatum") } features.append( {"type": "Feature", "geometry": multipolygon, "properties": properties,} ) geojson = {"type": "FeatureCollection", "features": [f for f in features]} return geojson
def makeClusterPolygons(self, clusters): # make polygons for each of those clusters clusterids = clusters['data_inert'].keys() if -1 in clusterids: clusterids.remove(-1) poly = [] for k in clusterids: points = np.asarray(clusters['data_inert'][k]) if k >= 0 and points.shape[0] > 2: hull = ConvexHull(points) hullvert = list(hull.vertices) coords = [(x, y) for x, y in points[hullvert, :]] poly.append((coords, )) mp = MultiPolygon(poly) color = '#ff0000' category = 'pca' st = { "weight": 2, "color": color, "opacity": 0, "fillColor": color, "fillOpacity": 0.3 } pr = {"name": category, "popupContent": category, "style": st} ft = Feature(geometry=mp, properties=pr) outfilename = 'sample-geojson.js' outfile = open(outfilename, 'w') print >> outfile, "var data = " geojson.dump(ft, outfile) #geojson.dump(ft,outfile) outfile.close()
def get_polygon(self,mgrs_list): try: # m_string = ';'.join(mgrs_list) # process = subprocess.Popen(["GeoConvert","-w","-g","-p","0","--input-string",m_string],stdout=subprocess.PIPE) # result = process.communicate()[0].rstrip().split('\n') #Note: This gives shell access, be careful to screen your inputs! m_string = '\n'.join(mgrs_list) shell_command = "printf '" + m_string + "' | GeoConvert -g -p -0" try: process = subprocess.check_output(shell_command, shell=True) result = process.rstrip().split('\n') except subprocess.CalledProcessError, e: result = e.output except Exception: import traceback errorCode = traceback.format_exc() raise ProgramException('Error executing GeoConvert program. errorCode='+errorCode+'. m_string='+m_string) for i, val in enumerate(result): result[i] = tuple(float(x) for x in val.split()) # Flip the lat/lngs for i, (lat, lon) in enumerate(result): result[i] = (lon,lat) return MultiPolygon([[result]])
def _convert(self): features = [] for record, shape in zip(self.shapefile.records(), self.shapefile.shapeRecords()): if len(shape.shape.parts) == 1: #make a polygon properties = {} for selection in self.selectedproperties: properties[selection] = str(record[self.properties.index(selection)]) polygon = Polygon([[tuple([round(i[0], self.coordprecision), round(i[1], self.coordprecision)]) for i in shape.shape.points]]) feature = Feature(geometry=polygon, properties=properties) elif len(shape.shape.parts) > 1: #make a multipart polygon properties = {} for selection in self.selectedproperties: properties[selection] = str(record[self.properties.index(selection)]) indices = list(shape.shape.parts) coords = [[tuple([round(i[0], self.coordprecision), round(i[1], self.coordprecision)]) for i in shape.shape.points]] parts = [] for i, index in enumerate(indices): try: parts.append(coords[index:indices[i+1]]) except: parts.append(coords[index:]) parts = [(i) for i in parts] multipolygon = MultiPolygon(parts) feature = Feature(geometry=multipolygon, properties=properties) else: print("no record made for ", record) feature = None if feature: features.append(feature) collection = FeatureCollection(features)
def getCategoryPolygons(self): catClust = self.clusters poly = [] for k in catClust.keys(): points = np.array([[a['longitude'], a['latitude']] for a in catClust[k]]) ids = [a['photo_id'] for a in catClust[k]] if k >= 0 and points.shape[0] > 2: hull = ConvexHull(points) hullvert = list(hull.vertices) coords = [(x, y) for x, y in points[hullvert, :]] # coords = alphashape.alpha_shape_wrapper(points,.01) poly.append((coords, )) for p, i in zip(points, ids): if i not in self.points_used.keys(): self.points_used[i] = { 'coordinates': p.tolist(), 'photo_id': i, 'categories': [self.category] } else: self.points_used[i]['categories'].append(self.category) mp = MultiPolygon(poly) self.category_multipolygon = mp
def tracerOut(tracerIn, dirctory, filOut): coor = [] layerType = { "type": "FeatureCollection", "totalFeatures": 0, "features": [], "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4326" } } } for k in range(len(tracerIn)): coor2 = [[[]]] coor = [tracerIn[k]['geometry']['coordinates'][0]] # print coor for xy in range(len(coor[0])): coor_unit = [ float(coor[0][xy][i]) for i in range(len(coor[0][xy])) ] coor2[0][0].append(coor_unit) layer = MultiPolygon(coordinates=coor2) inFeatures = {"type": "Feature", "properties": {}, "geometry": layer} layerType['features'].append(inFeatures) layerType['totalFeatures'] = k + 1 dataOut = json.dumps(layerType, sort_keys=True) f = open(dirctory + filOut, 'wb') f.write(dataOut) f.close() return
def find_countries(self): self.countries_of_interest = set() collection = FeatureCollection(self.project_data['tasks']['features']) project_tasks = gpd.GeoDataFrame.from_features(collection) #print(project_tasks.head(1)) project_multipolygon = MultiPolygon(self.project_data['areaOfInterest']['coordinates']) shapely_multipolygon = sgeom.shape(project_multipolygon) countries = gpd.read_file(os.path.join(os.getcwd(), 'ne_10m_admin_0_countries', 'ne_10m_admin_0_countries.shp')) for index, project_task in project_tasks.iterrows(): for index2, country in countries.iterrows(): if project_task['geometry'].intersects(country['geometry']) and country['SOVEREIGNT'] not in self.countries_of_interest: self.countries_of_interest.add(country['SOVEREIGNT']) print(country['SOVEREIGNT']) # cond = Condition() # cond.acquire() # while True: # cond.wait() if len(self.countries_of_interest) == 0: return False return True
def get_grouped_fc_from_1d_array(self, values, triangles, property_name, decimals): rounded = values.round(decimals=decimals) unique = np.unique(rounded) features = [] for u in unique: matching = np.where(rounded == u) matching_triangles = (triangles[matching]) dtype = matching_triangles.dtype.descr shape = matching_triangles.shape + (len(dtype), ) coordinates = (matching_triangles.view( dtype='<f8').reshape(shape).tolist()) prop_fmt = '{{:.{}f}}'.format(decimals) properties = {'{}'.format(property_name): prop_fmt.format(u)} feature = Feature(id="1", properties=properties, geometry=MultiPolygon(coordinates=coordinates)) features.append(feature) return FeatureCollection(features)
def get_geojson_geometry(self): # If the bbox crosses the antimeridian, export as a multipolygon. if self.west > self.east: return MultiPolygon([ # Western side. ([ (self.west, self.south), (180.0, self.south), (180.0, self.north), (self.west, self.north), (self.west, self.south), ]), # Eastern side. ([ (-180.0, self.south), (self.east, self.south), (self.east, self.north), (-180.0, self.north), (-180.0, self.south), ]) ]) # Non-antimeridian-crossing areas. else: return Polygon([[ (self.west, self.south), (self.east, self.south), (self.east, self.north), (self.west, self.north), (self.west, self.south), ]])
def to_geojson(data, geom_type): """Convert JSON to GeoJSON""" collection = [] for dat in data: if geom_type == 'MultiPolygon': coordinates = MultiPolygon(dat['coordinates']) elif geom_type == 'Point': coordinates = Point(dat['coordinates']) elif geom_type == 'LineString': coordinates = LineString(dat['coordinates']) else: raise NotImplementedError() properties = { key: value for key, value in dat.items() if key not in ['geom', 'coordinates', 'geom_type'] } feature_coordinates = Feature(geometry=coordinates, properties=properties) collection.append(feature_coordinates) feature_collection = FeatureCollection(collection) return feature_collection
def _genContourPolygons(self, CSs): ''' Implements the Contour and Polygon classes to sort out the holes before creating geojson MultiPolygon Features for each Contour. ''' newPlys = self._cleanContours(CSs) countryGroup = [] for plys in newPlys: contourList = [] for group in plys: contour = Contour(group) contour.createHoles() contourList.append(contour) countryGroup.append(contourList) featureAr = [] for clusterNum, contourList in enumerate(countryGroup): for index, contour in enumerate(contourList): geoPolys = [] for polygon in contour.polygons: geoPolys.append(polygon.points) newMultiPolygon = MultiPolygon(geoPolys) newFeature = Feature(geometry=newMultiPolygon, properties={ "contourNum": index, "clusterNum": clusterNum, "identity": str(index) + str(clusterNum) }) featureAr.append(newFeature) return featureAr
def multipolygon(self, count_limit=10): """ Returns a specific number of randomly arranged polygons with a random number of nodes """ return MultiPolygon([ self.polygon(node_limit=randint(3, 11)) for i in range(count_limit) ])
def test_boolean_point_in_polygon(): point = Feature(geometry=Point((-77, 44))) polygon = Feature(geometry=MultiPolygon([ ([(-81, 41), (-81, 47), (-72, 47), (-72, 41), (-81, 41)], ), ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)], ), ])) bpp = boolean_point_in_polygon(point, polygon) assert bpp == True
def build_multi_polygon(self): polygons = [] idx = 0 while idx >= 0: polygons.append(self.build_polygon(idx)) [next, _, _, _] = self.hierarchy[idx] idx = next multi_polygon = MultiPolygon(polygons) return Feature(geometry = multi_polygon, properties = { 'bottom': int(self.bottom), 'top': int(self.top) })
def get_polygon(self,mgrs_list): m_string = ';'.join(mgrs_list) process = subprocess.Popen(["GeoConvert","-w","-g","-p","0","--input-string",m_string],stdout=subprocess.PIPE) result = process.communicate()[0].rstrip().split('\n') for i,val in enumerate(result): result[i] = tuple(float(x) for x in val.split()) return MultiPolygon([[result]])
def to_geojson(self): wrapper = copy.deepcopy(self.tags) wrapper['bounding-boxes'] = [ c.bbox for c in country_subunits_by_iso_code(self.iso2) ] wrapper.update(hooks.get_additional_tags(self)) main_data = MultiPolygon(self.polygons) feature = Feature(geometry=main_data, properties=wrapper) return geojson.dumps(FeatureCollection([feature]), sort_keys=True)
def test_bbox_multi_polygon(): mp = MultiPolygon( [ ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],), ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91), (23.18, -34.29),],), ] ) bb = bbox(mp) assert bb[0] == -130.91 assert bb[1] == -34.29 assert bb[2] == 35.12 assert bb[3] == 77.91
def _generateJSONFeature(self, index, continents): ''' Creates the geojson geometries with the necessary properties. ''' label = Utils.read_tsv(self.regionFile) shapeList = [] for child in continents: polygon = child.points shapeList.append(polygon) newMultiPolygon = MultiPolygon(shapeList) properties = {"clusterNum": index, "labels": label["label"][index]} return Feature(geometry=newMultiPolygon, properties=properties)
def __init__(self, input_params: List[QajsonParam]): super().__init__(input_params) self._depth_error = self.get_param('Constant Depth Error') self._depth_error_factor = self.get_param( 'Factor of Depth Dependent Errors') self.tiles_geojson = MultiPolygon() # amount of padding to place around failing pixels # this simplifies the geometry, and enlarges the failing area that # will allow it to be shown in the UI more easily self.pixel_growth = 5
def test_dumps_multipolygon2D(self): from chsdi.esrigeojsonencoder import dumps as esri_dumps from geojson import MultiPolygon point = MultiPolygon([([(600000, 200000), (650000, 250000), (700000, 250000), (600000, 2000)], ), ([(600000, 200000), (650000, 250000), (700000, 250000), (600000, 2000)], )], properties={'name': 'toto'}) result = esri_dumps(point) self.assertEqual( result, '{"attributes": {"name": "toto"}, "rings": [[[600000, 200000], [650000, 250000], [700000, 250000], [600000, 2000]], [[600000, 200000], [650000, 250000], [700000, 250000], [600000, 2000]]], "spatialReference": {"wkid": 21781}}' )
def _generateJSONFeature(self, clusterId, continents): ''' Creates the geojson geometries with the necessary properties. ''' labels = Utils.read_features(self.regionFile) shapeList = [] for child in continents: polygon = child.points shapeList.append(polygon) newMultiPolygon = MultiPolygon(shapeList) label = labels[clusterId].get("label", "Unknown") properties = {"clusterId": clusterId, "labels": label} return Feature(geometry=newMultiPolygon, properties=properties)
def __init__(self, input_params: List[QajsonParam]): super().__init__(input_params) # if any node has fewer soundings than this value, it will fail self._min_spn = self.get_param('Minimum Soundings per node') # if a percentage `_min_spn_p` of all nodes is above a threshold # `_min_spn_ap` then this check will also fail self._min_spn_p = self.get_param( 'Minumum Soundings per node percentage') self._min_spn_ap = self.get_param( 'Minimum Soundings per node at percentage') self.tiles_geojson = MultiPolygon() # amount of padding to place around failing pixels # this simplifies the geometry, and enlarges the failing area that # will allow it to be shown in the UI more easily self.pixel_growth = 5
def get_geometry(granule): multipolygon = [] for poly in granule.Spatial.HorizontalSpatialDomain.Geometry.GPolygon: ring = [] for point in poly.Boundary.Point: geojson_point = [ float(point.PointLongitude.cdata), float(point.PointLatitude.cdata), ] ring.append(geojson_point) closing_point = [ float(poly.Boundary.Point[0].PointLongitude.cdata), float(poly.Boundary.Point[0].PointLatitude.cdata), ] ring.append(closing_point) ringtuple = (ring, ) multipolygon.append(ringtuple) geometry = MultiPolygon(multipolygon) return geometry
def geohash_to_multipolygon(self, geohashes, simplify=False): polys = [] for g in geohashes: box = bbox(g) polys.append( Polygon([ (box['w'], box['n']), (box['e'], box['n']), (box['e'], box['s']), (box['w'], box['s']), ])) if simplify: polys = cascaded_union(polys) else: polys = MultiPolygon(polys) return mapping(polys)
def geojsonify(js): features = [] for ca in js['features']: geometry = MultiPolygon(coordinates=ca['geometry']['coordinates']) cap = ca['properties'] try: properties = { "community": cap["community"], "area_numbe": cap["area_numbe"], "hs_diploma_or_less": ca["hs_diploma_or_less"], "racial_majority": ca["racial_majority"], "unemployment": ca["unemployment"], "vacancy": ca["vacancy"], "poverty": ca["poverty"], "property": ca["property_crime_rate"], "violent": ca["violent_crime_rate"], } except Exception, e: import ipdb ipdb.set_trace() feature = Feature(geometry=geometry, properties=properties) features.append(feature)
def __init__(self, info): for name, data in info.items(): if name == 'geocode': self[name] = combine(data) elif name == 'areaDesc': self[name] = data elif name == 'polygon': self[name] = data if isinstance(data, str): if ' ' not in data: logger.error("Bad Polygon") return None self['location'] = Polygon(convertGeo(data)) elif isinstance(data, list): polydict = [] for poly in data: polydict.append(convertGeo(poly)) self['location'] = MultiPolygon(polydict) else: self['location'] = {'type': 'unsupported'} logger.error("Unsupported type of polygon area: {}".format( type(data))) elif name == 'circle': # <circle>51.507709,-99.233116 2.26</circle> # There is no GeoJSON Cicle types, thus needs to be converted to a polygon of sides circlePoint = data.split(' ')[0] circleSize = float(data.split(' ')[1]) * 1000 point = shapely.geometry.Point([ float(circlePoint.split(',')[1]), float(circlePoint.split(',')[0]) ]) angles = np.linspace(0, 360, 40) polygon = geog.propagate(point, angles, circleSize) self['location'] = shapely.geometry.mapping( shapely.geometry.Polygon(polygon)) else: logger.error("Unsupported Geo Type: {}".format(name))
def __init__(self, input_params: List[QajsonParam]): super().__init__(input_params) self._fds_multiplier = self.get_param( 'Feature Detection Size Multiplier') self._threshold_depth = self.get_param('Threshold Depth') self._a_fds_depth_multiplier = self.get_param( 'Above Threshold FDS Depth Multiplier') self._a_fds_depth_constant = self.get_param( 'Above Threshold FDS Depth Constant') self._b_fds_depth_multiplier = self.get_param( 'Below Threshold FDS Depth Multiplier') self._b_fds_depth_constant = self.get_param( 'Below Threshold FDS Depth Constant') self.tiles_geojson = MultiPolygon() # amount of padding to place around failing pixels # this simplifies the geometry, and enlarges the failing area that # will allow it to be shown in the UI more easily self.pixel_growth = 5
def test_points_within_polygon(): f1 = Feature(geometry=Point((-46.6318, -23.5523))) f2 = Feature(geometry=Point((-46.6246, -23.5325))) f3 = Feature(geometry=Point((-46.6062, -23.5513))) f4 = Feature(geometry=Point((-46.663, -23.554))) f5 = Feature(geometry=Point((-46.643, -23.557))) f6 = Feature(geometry=Point((-73, 45))) f7 = Feature(geometry=Point((36, 71))) points = FeatureCollection([f1, f2, f3, f4, f5, f6, f7]) poly = Polygon([[ (-46.653, -23.543), (-46.634, -23.5346), (-46.613, -23.543), (-46.614, -23.559), (-46.631, -23.567), (-46.653, -23.560), (-46.653, -23.543), ]]) fpoly = Feature(geometry=poly) poly2 = Polygon([[ (-76.653, -11.543), (-46.634, -23.5346), (-46.613, -23.543), (-46.614, -23.559), (-46.631, -23.567), (-46.653, -23.560), (-76.653, -11.543), ]]) fpoly2 = Feature(geometry=poly2) fc = FeatureCollection([fpoly, fpoly2]) result = points_within_polygon(points, fc) assert result == { "features": [ { "geometry": { "coordinates": [-46.6318, -23.5523], "type": "Point" }, "properties": {}, "type": "Feature", }, { "geometry": { "coordinates": [-46.643, -23.557], "type": "Point" }, "properties": {}, "type": "Feature", }, ], "type": "FeatureCollection", } multi_polygon = Feature(geometry=MultiPolygon([ ([(-81, 41), (-81, 47), (-72, 47), (-72, 41), (-81, 41)], ), ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)], ), ])) result2 = points_within_polygon(f6, multi_polygon) assert result2 == { "features": [{ "geometry": { "coordinates": [-73, 45], "type": "Point" }, "properties": {}, "type": "Feature", }], "type": "FeatureCollection", }