def __init__(self, geom_input, srs=None): "Initializes Geometry on either WKT or an OGR pointer as input." str_instance = isinstance(geom_input, basestring) # If HEX, unpack input to to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = buffer(a2b_hex(geom_input.upper())) str_instance = False # Constructing the geometry, if str_instance: # Checking if unicode if isinstance(geom_input, unicode): # Encoding to ASCII, WKT or HEX doesn't need any more. geom_input = geom_input.encode('ascii') wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('srid'): # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m.group('srid')) if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt')))) else: g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt'))), None, byref(c_void_p())) elif json_m: g = capi.from_json(geom_input) else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). ogr_t = OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, buffer): # WKB was passed in g = capi.from_wkb(str(geom_input), None, byref(c_void_p()), len(geom_input)) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise OGRException('Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if bool(srs): self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num]
def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects, and may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword is used to specify the Source Reference Identifier (SRID) number for this Geometry. If not set, the SRID will be None. """ input_srid = None if isinstance(geo_input, bytes): geo_input = force_text(geo_input) if isinstance(geo_input, str): wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handling WKT input. if wkt_m.group('srid'): input_srid = int(wkt_m.group('srid')) g = wkt_r().read(force_bytes(wkt_m.group('wkt'))) elif hex_regex.match(geo_input): # Handling HEXEWKB input. g = wkb_r().read(force_bytes(geo_input)) elif json_regex.match(geo_input): # Handling GeoJSON input. g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb) else: raise ValueError( 'String input unrecognized as WKT EWKT, and HEXEWKB.') elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geometry (GEOM_PTR). g = geo_input elif isinstance(geo_input, memoryview): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: # Invalid geometry type. raise TypeError('Improper geometry input type: %s' % type(geo_input)) if not g: raise GEOSException( 'Could not initialize GEOS Geometry with given input.') input_srid = input_srid or capi.geos_get_srid(g) or None if input_srid and srid and input_srid != srid: raise ValueError('Input geometry already has SRID: %d.' % input_srid) # Setting the pointer object with a valid pointer. self.ptr = g # Post-initialization setup. self._post_init(input_srid or srid)
def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects, and may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword is used to specify the Source Reference Identifier (SRID) number for this Geometry. If not set, the SRID will be None. """ input_srid = None if isinstance(geo_input, bytes): geo_input = force_text(geo_input) if isinstance(geo_input, str): wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handling WKT input. if wkt_m.group('srid'): input_srid = int(wkt_m.group('srid')) g = self._from_wkt(force_bytes(wkt_m.group('wkt'))) elif hex_regex.match(geo_input): # Handling HEXEWKB input. g = wkb_r().read(force_bytes(geo_input)) elif json_regex.match(geo_input): # Handling GeoJSON input. ogr = gdal.OGRGeometry.from_json(geo_input) g = ogr._geos_ptr() input_srid = ogr.srid else: raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.') elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geometry (GEOM_PTR). g = geo_input elif isinstance(geo_input, memoryview): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: # Invalid geometry type. raise TypeError('Improper geometry input type: %s' % type(geo_input)) if not g: raise GEOSException('Could not initialize GEOS Geometry with given input.') input_srid = input_srid or capi.geos_get_srid(g) or None if input_srid and srid and input_srid != srid: raise ValueError('Input geometry already has SRID: %d.' % input_srid) # Setting the pointer object with a valid pointer. self.ptr = g # Post-initialization setup. self._post_init(input_srid or srid)
def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects. It may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword specifies the Source Reference Identifier (SRID) number for this Geometry. If not provided, it defaults to None. """ input_srid = None if isinstance(geo_input, bytes): geo_input = force_text(geo_input) if isinstance(geo_input, str): wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handle WKT input. if wkt_m.group('srid'): input_srid = int(wkt_m.group('srid')) g = self._from_wkt(force_bytes(wkt_m.group('wkt'))) elif hex_regex.match(geo_input): # Handle HEXEWKB input. g = wkb_r().read(force_bytes(geo_input)) elif json_regex.match(geo_input): # Handle GeoJSON input. ogr = gdal.OGRGeometry.from_json(geo_input) g = ogr._geos_ptr() input_srid = ogr.srid else: raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.') elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geometry (GEOM_PTR). g = geo_input elif isinstance(geo_input, memoryview): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: raise TypeError('Improper geometry input type: %s' % type(geo_input)) if not g: raise GEOSException('Could not initialize GEOS Geometry with given input.') input_srid = input_srid or capi.geos_get_srid(g) or None if input_srid and srid and input_srid != srid: raise ValueError('Input geometry already has SRID: %d.' % input_srid) super().__init__(g, None) # Set the SRID, if given. srid = input_srid or srid if srid and isinstance(srid, int): self.srid = srid
def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects, and may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword is used to specify the Source Reference Identifier (SRID) number for this Geometry. If not set, the SRID will be None. """ if isinstance(geo_input, basestring): if isinstance(geo_input, unicode): # Encoding to ASCII, WKT or HEXEWKB doesn't need any more. geo_input = geo_input.encode('ascii') wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handling WKT input. if wkt_m.group('srid'): srid = int(wkt_m.group('srid')) g = wkt_r().read(wkt_m.group('wkt')) elif hex_regex.match(geo_input): # Handling HEXEWKB input. g = wkb_r().read(geo_input) elif gdal.HAS_GDAL and json_regex.match(geo_input): # Handling GeoJSON input. g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb) else: raise ValueError( 'String or unicode input unrecognized as WKT EWKT, and HEXEWKB.' ) elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geomtry (GEOM_PTR). g = geo_input elif isinstance(geo_input, buffer): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: # Invalid geometry type. raise TypeError('Improper geometry input type: %s' % str(type(geo_input))) if bool(g): # Setting the pointer object with a valid pointer. self.ptr = g else: raise GEOSException( 'Could not initialize GEOS Geometry with given input.') # Post-initialization setup. self._post_init(srid)
def __init__(self, geom_input, srs=None): "Initializes Geometry on either WKT or an OGR pointer as input." str_instance = isinstance(geom_input, six.string_types) # If HEX, unpack input to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = six.memoryview(a2b_hex(geom_input.upper().encode())) str_instance = False # Constructing the geometry, if str_instance: wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('srid'): # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m.group('srid')) if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt').encode()))) else: g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt').encode())), None, byref(c_void_p())) elif json_m: g = capi.from_json(geom_input.encode()) else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, six.memoryview): # WKB was passed in g = capi.from_wkb(bytes(geom_input), None, byref(c_void_p()), len(geom_input)) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise GDALException('Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise GDALException('Cannot create OGR Geometry from input: %s' % str(geom_input)) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if srs: self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num]
def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects, and may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword is used to specify the Source Reference Identifier (SRID) number for this Geometry. If not set, the SRID will be None. """ if isinstance(geo_input, bytes): geo_input = force_text(geo_input) if isinstance(geo_input, six.string_types): wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handling WKT input. if wkt_m.group("srid"): srid = int(wkt_m.group("srid")) g = wkt_r().read(force_bytes(wkt_m.group("wkt"))) elif hex_regex.match(geo_input): # Handling HEXEWKB input. g = wkb_r().read(force_bytes(geo_input)) elif json_regex.match(geo_input): # Handling GeoJSON input. if not gdal.HAS_GDAL: raise ValueError("Initializing geometry from JSON input requires GDAL.") g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb) else: raise ValueError("String or unicode input unrecognized as WKT EWKT, and HEXEWKB.") elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geometry (GEOM_PTR). g = geo_input elif isinstance(geo_input, six.memoryview): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: # Invalid geometry type. raise TypeError("Improper geometry input type: %s" % str(type(geo_input))) if g: # Setting the pointer object with a valid pointer. self.ptr = g else: raise GEOSException("Could not initialize GEOS Geometry with given input.") # Post-initialization setup. self._post_init(srid)
def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects, and may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword is used to specify the Source Reference Identifier (SRID) number for this Geometry. If not set, the SRID will be None. """ if isinstance(geo_input, basestring): if isinstance(geo_input, unicode): # Encoding to ASCII, WKT or HEXEWKB doesn't need any more. geo_input = geo_input.encode('ascii') wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handling WKT input. if wkt_m.group('srid'): srid = int(wkt_m.group('srid')) g = wkt_r().read(wkt_m.group('wkt')) elif hex_regex.match(geo_input): # Handling HEXEWKB input. g = wkb_r().read(geo_input) elif gdal.HAS_GDAL and json_regex.match(geo_input): # Handling GeoJSON input. g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb) else: raise ValueError('String or unicode input unrecognized as WKT EWKT, and HEXEWKB.') elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geomtry (GEOM_PTR). g = geo_input elif isinstance(geo_input, buffer): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: # Invalid geometry type. raise TypeError('Improper geometry input type: %s' % str(type(geo_input))) if bool(g): # Setting the pointer object with a valid pointer. self.ptr = g else: raise GEOSException('Could not initialize GEOS Geometry with given input.') # Post-initialization setup. self._post_init(srid)
def search(request, groups=['public']): data = {} if request.body: data = json.loads(request.body) sat_id = data.get('sat_id', []) const_id = data.get('const_id', []) if 'MO' in const_id: sat_id.append('Terra') const_id.append('modis09') const_id.remove('MO') if 'MY' in const_id: sat_id.append('Aqua') const_id.append('modis09') const_id.remove('MY') geom = data.get('geom') date = data.get('date', 'acquired') start_time = data.get('start_time') end_time = data.get('end_time') cloud_fraction = data.get('cloud_fraction') cloud_fraction_0 = data.get('cloud_fraction_0') fill_fraction = data.get('fill_fraction') offset = int(data.get('offset', '0')) limit = int(data.get('limit', '100')) params = data.get('params') sort = data.get('sort', False) bbox = data.get('bbox', False) limit = min(limit, 10000) sources = Source.objects.filter(groups__overlap=groups) if const_id: sources = sources.filter(const_id__in=const_id) if sat_id: sources = sources.filter(sat_id__in=sat_id) features = [] if sources.exists(): qs = Metadata.objects.filter(source__in=sources).filter( groups__overlap=groups).only('id', date) if geom: # first check if wkt string if not wkt_regex.match(geom): try: geom_tmp = json.loads(geom) except ValueError as e: return HttpResponseBadRequest(e.message) else: if 'geometry' in geom_tmp: geom = json.dumps(geom_tmp['geometry']) elif 'coordinates' not in geom_tmp: return HttpResponseBadRequest( 'supported geojson types include: Feature and Geometry Primitives' ) try: geos_geom = GEOSGeometry(geom) except: return HttpResponseBadRequest("invalid geometry") if bbox in ['true', True]: qs = qs.filter(geom__bboverlaps=geos_geom) else: qs = qs.filter(geom__intersects=geos_geom) if start_time: try: qs = qs.filter(**{'%s__gte' % date: parse(start_time)}) except: return HttpResponseBadRequest('invalid start_time') if end_time: try: qs = qs.filter(**{'%s__lte' % date: parse(end_time)}) except: return HttpResponseBadRequest('invalid end_time') if cloud_fraction is not None: try: qs = qs.filter(cloud_fraction__gte=0).filter( cloud_fraction__lte=float(cloud_fraction)) except: return HttpResponseBadRequest('invalid cloud_fraction') if cloud_fraction_0 is not None: try: qs = qs.filter(cloud_fraction_0__gte=0).filter( cloud_fraction_0__lte=float(cloud_fraction_0)) except: return HttpResponseBadRequest('invalid cloud_fraction_0') if fill_fraction is not None: try: qs = qs.filter(fill_fraction__gte=float(fill_fraction)) except: return HttpResponseBadRequest('invalid fill_fraction') if params: qs = qs.filter(data__contains=params) if sort in ['true', True]: qs = qs.order_by('%s' % date) else: qs = qs.order_by('id') for metadata in Metadata.objects.filter( id__in=qs.values_list('id')[:1000]).only( 'key', 'geom', 'data')[offset:limit + offset]: feature = {} feature['id'] = metadata.key feature['type'] = 'Feature' feature['bbox'] = metadata.geom.extent feature['properties'] = metadata.data feature['geometry'] = json.loads(metadata.geom.json) features.append(feature) return HttpResponse(json.dumps(features), content_type='application/json')
def summary(request, groups=['public']): data = {} if request.body: data = json.loads(request.body) sat_id = data.get('sat_id', []) const_id = data.get('const_id', []) geom = data.get('geom') date = data.get('date', 'acquired') part = data.get('part') start_time = data.get('start_time') end_time = data.get('end_time') cloud_fraction = data.get('cloud_fraction') cloud_fraction_0 = data.get('cloud_fraction_0') fill_fraction = data.get('fill_fraction') params = data.get('params') bbox = data.get('bbox', False) result = {} sources = Source.objects.filter(groups__overlap=groups) if const_id: sources = sources.filter(const_id__in=const_id) if sat_id: sources = sources.filter(sat_id__in=sat_id) if sources.exists(): qs = Metadata.objects.filter(source__in=sources).filter( groups__overlap=groups) if geom: # first check if wkt string if not wkt_regex.match(geom): try: geom_tmp = json.loads(geom) except ValueError as e: return HttpResponseBadRequest(e.message) else: if 'geometry' in geom_tmp: geom = json.dumps(geom_tmp['geometry']) elif 'coordinates' not in geom_tmp: return HttpResponseBadRequest( 'supported geojson types include: Feature and Geometry Primitives' ) try: geos_geom = GEOSGeometry(geom) except: return HttpResponseBadRequest("invalid geometry") if bbox in ['true', True]: qs = qs.filter(geom__bboverlaps=geos_geom) else: qs = qs.filter(geom__intersects=geos_geom) if start_time: try: qs = qs.filter(**{'%s__gte' % date: parse(start_time)}) except: return HttpResponseBadRequest('invalid start_time') if end_time: try: qs = qs.filter(**{'%s__lte' % date: parse(end_time)}) except: return HttpResponseBadRequest('invalid end_time') if cloud_fraction is not None: try: qs = qs.filter(cloud_fraction__gte=0).filter( cloud_fraction__lte=float(cloud_fraction)) except: return HttpResponseBadRequest('invalid cloud_fraction') if cloud_fraction_0 is not None: try: qs = qs.filter(cloud_fraction_0__gte=0).filter( cloud_fraction_0__lte=float(cloud_fraction_0)) except: return HttpResponseBadRequest('invalid cloud_fraction_0') if fill_fraction is not None: try: qs = qs.filter(fill_fraction__gte=float(fill_fraction)) except: return HttpResponseBadRequest('invalid fill_fraction') if params: qs = qs.filter(data__contains=params) if part: result['items'] = sorted([{ 'date': datetime.strftime(d['date'], '%Y-%m-%dT%H:%M:00'), 'bytes': d['bytes'], 'pixels': d['pixels'], 'count': d['count'] } for d in qs.extra({ 'date': "date_trunc('%s', %s)" % (part, date) }).values('date').annotate( count=Count('pk'), bytes=Sum('bytes'), pixels=Sum('pixels'))], key=itemgetter('date')) result['count'] = sum([d['count'] for d in result['items']]) result['bytes'] = sum([d['bytes'] for d in result['items']]) result['pixels'] = sum([d['pixels'] for d in result['items']]) result['const_id'] = const_id else: result = qs.aggregate(count=Count('pk'), bytes=Sum('bytes'), pixels=Sum('pixels')) result['const_id'] = const_id return HttpResponse(json.dumps(result), content_type='application/json')
* strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword specifies the Source Reference Identifier (SRID) number for this Geometry. If not provided, it defaults to None. """ input_srid = None if isinstance(geo_input, bytes): geo_input = force_text(geo_input) if isinstance(geo_input, str): wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handle WKT input. if wkt_m.group('srid'): input_srid = int(wkt_m.group('srid')) g = self._from_wkt(force_bytes(wkt_m.group('wkt'))) elif hex_regex.match(geo_input): # Handle HEXEWKB input. g = wkb_r().read(force_bytes(geo_input)) elif json_regex.match(geo_input): # Handle GeoJSON input. ogr = gdal.OGRGeometry.from_json(geo_input) g = ogr._geos_ptr() input_srid = ogr.srid else: raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.')