def setupTreemapEnv(): def local_render_to_response(*args, **kwargs): from django.template import loader from django.http import HttpResponse hr = HttpResponse(loader.render_to_string(*args, **kwargs)) if hasattr(args[1], 'dicts'): hr.request_context = args[1].dicts return hr django.shortcuts.render_to_response = local_render_to_response instance = make_instance(is_public=True) create_stewardship_udfs(instance) make_user_with_default_role(instance, 'jim') commander = make_commander_user(instance, 'commander') make_apprentice_user(instance, 'apprentice') n1geom = MultiPolygon(Polygon( ((0, 0), (100, 0), (100, 100), (0, 100), (0, 0)))) n2geom = MultiPolygon( Polygon(((0, 101), (101, 101), (101, 200), (0, 200), (0, 101)))) n1 = Boundary(name="n1", category='blah', sort_order=4, geom=n1geom) n2 = Boundary(name="n2", category='blah', sort_order=4, geom=n2geom) n1.save() n2.save() s1 = Species(otm_code="s1", genus="testus1", species="specieius1", cultivar='', instance=instance) s2 = Species(otm_code="s2", genus="testus2", species="specieius2", cultivar='', instance=instance) s3 = Species(otm_code="s3", genus="testus2", species="specieius3", cultivar='', instance=instance) s1.is_native = True s1.fall_conspicuous = True s1.flower_conspicuous = True s1.palatable_human = True s2.is_native = True s2.fall_conspicuous = False s2.flower_conspicuous = True s2.palatable_human = False s2.has_wildlife_value = True s3.has_wildlife_value = True s1.save_with_user(commander) s2.save_with_user(commander) s3.save_with_user(commander) return instance
def rack_requested_kml(request): try: page_number = int(request.REQUEST.get('page_number', '1')) except ValueError: page_number = 1 try: page_size = int(request.REQUEST.get('page_size', sys.maxint)) except ValueError: page_size = sys.maxint # Get bounds from request. bbox = request.REQUEST.get('bbox') if bbox: bbox = [float(n) for n in bbox.split(',')] assert len(bbox) == 4 geom = Polygon.from_bbox(bbox) racks = Rack.objects.filter(location__contained=geom) else: racks = Rack.objects.all() racks = racks.order_by(*DEFAULT_RACK_ORDER) paginator = Paginator(racks, page_size) page_number = min(page_number, paginator.num_pages) page = paginator.page(page_number) return render_to_kml("placemarkers.kml", {'racks' : racks, 'page': page, 'page_size': page_size, })
def new_item(request): if request.method == 'POST': item_json_obj = json.loads(request.POST['map-json']) item_obj = Item() item_obj.owner = request.user item_obj.name = item_json_obj['name'] item_obj.title = item_json_obj['title'] item_obj.url = item_json_obj['url'] item_obj.type = item_json_obj['type'] item_obj.type_keywords = ",".join(item_json_obj['typeKeywords']) item_obj.description = item_json_obj['description'] item_obj.tags = ",".join(item_json_obj['tags']) item_obj.snippet = item_json_obj['snippet'] item_obj.thumbnail = item_json_obj['thumbnail'] if item_json_obj['extent']: item_obj.extent = Polygon.from_bbox(item_json_obj['extent'][0] + item_json_obj['extent'][1]) item_obj.created = datetime.datetime.today() item_obj.modified = datetime.datetime.today() item_obj.save() if 'text' in item_json_obj: item_data_obj = ItemData(item=item_obj, text=json.dumps(item_json_obj['text'])) item_data_obj.save() return redirect(reverse('content.edit_item', args=[item_obj.id])) else: return render(request, 'content/edit_item.html')
def _spatial_extent_(self): min_x = float(self.dataset.variables[self.colbnds_name][:].min()) min_y = float(self.dataset.variables[self.rowbnds_name][:].min()) max_x = float(self.dataset.variables[self.colbnds_name][:].max()) max_y = float(self.dataset.variables[self.rowbnds_name][:].max()) p = Polygon(((min_x,min_y),(max_x,min_y),(max_x,max_y),(min_x,max_y),(min_x,min_y)),srid=4326) return(p)
def save(self, *args, **kwargs): if self.extent_lat_min is not None and self.extent_long_min is not None and self.extent_lat_max is not None and \ self.extent_long_max is not None: self.geometry = Polygon.from_bbox((self.extent_long_min, self.extent_lat_min, self.extent_long_max, self.extent_lat_max)) super(Project, self).save(*args, **kwargs)
def build_proposal_query_dict(d): subqueries = {} ids = run_attributes_query(d) or [] if "id" in d: ids = re.split(r"\s*,\s*", d["id"]) if "text" in d: subqueries["address__icontains"] = d["text"] if d.get("region"): regions = re.split(r"\s*;\s*", d["region"]) subqueries["region_name__in"] = regions if ids: subqueries["pk__in"] = ids if "projects" in d: if d["projects"] == "null": subqueries["project__isnull"] = True elif d["projects"] == "all": subqueries["project__isnull"] = False if "lotsize" in d: parcel_query = make_size_query(d["lotsize"]) if parcel_query: parcel_ids = LotSize.objects.filter( **parcel_query).values("parcel_id") subqueries["parcel_id__in"] = parcel_ids bounds = d.get("box") if bounds: coords = [float(coord) for coord in bounds.split(",")] # Coordinates are submitted to the server as # latMin,longMin,latMax,longMax, but from_bbox wants its arguments in a # different order: bbox = Polygon.from_bbox((coords[1], coords[0], coords[3], coords[2])) subqueries["location__within"] = bbox # If status is anything other than 'active' or 'closed', find all # proposals. status = d.get("status", "active").lower() if status == "closed": subqueries["complete"] = True elif status == "active": subqueries["complete"] = False event = d.get("event") if event: try: subqueries["event"] = int(event) except ValueError: pass for k in d: if k in query_params: subqueries[query_params[k]] = d[k] return subqueries
def handle(self, *args, **options): verbosity = options.get('verbosity') file_path = options.get('file_path') area_type_name = options.get('area_type') name_column = options.get('name') encoding = options.get('encoding') srid = options.get('srid') do_intersect = options.get('intersect') bbox = Polygon.from_bbox(settings.SPATIAL_EXTENT) bbox.srid = settings.SRID ds = DataSource(file_path, encoding=encoding) count_error = 0 area_type, created = RestrictedAreaType.objects.get_or_create( name=area_type_name) if verbosity > 0: self.stdout.write("RestrictedArea Type's %s created" % area_type_name if created else "Get %s" % area_type_name) for layer in ds: for feat in layer: try: geom = feat.geom.geos if not isinstance(geom, Polygon) and not isinstance( geom, MultiPolygon): if verbosity > 0: self.stdout.write( "%s's geometry is not a polygon" % feat.get(name_column)) break elif isinstance(geom, Polygon): geom = MultiPolygon(geom) self.check_srid(srid, geom) geom.dim = 2 if geom.valid: if do_intersect and bbox.intersects( geom) or not do_intersect and geom.within( bbox): instance, created = RestrictedArea.objects.update_or_create( name=feat.get(name_column), area_type=area_type, defaults={'geom': geom}) if verbosity > 0: self.stdout.write( "%s %s" % ('Created' if created else 'Updated', feat.get(name_column))) else: if verbosity > 0: self.stdout.write("%s's geometry is not valid" % feat.get(name_column)) except IndexError: if count_error == 0: self.stdout.write( "Name's attribute do not correspond with options\n" "Please, use --name to fix it.\n" "Fields in your file are : %s" % ', '.join(layer.fields)) count_error += 1
def build_proposal_query_dict(d): subqueries = {} ids = build_attributes_query(d) or [] if "id" in d: ids = re.split(r"\s*,\s*", d["id"]) if "text" in d: subqueries["address__icontains"] = d["text"] if d.get("region"): regions = re.split(r"\s*,\s*", d["region"]) regions = [region_names[r] for r in regions if r in region_names] if len(regions) == 1: subqueries["region_name"] = regions[0] else: subqueries["region_name__in"] = regions if ids: subqueries["pk__in"] = ids if "projects" in d: if d["projects"] == "null": subqueries["project__isnull"] = True elif d["projects"] == "all": subqueries["project__isnull"] = False # else: # subqueries["projects"] = d["project"] bounds = d.get("box") if bounds: coords = [float(coord) for coord in bounds.split(",")] # Coordinates are submitted to the server as # latMin,longMin,latMax,longMax, but from_bbox wants its arguments in a # different order: bbox = Polygon.from_bbox((coords[1], coords[0], coords[3], coords[2])) subqueries["location__within"] = bbox # If status is anything other than 'active' or 'closed', find all # proposals. status = d.get("status", "active").lower() if status == "closed": subqueries["complete"] = True elif status == "active": subqueries["complete"] = False event = d.get("event") if event: try: subqueries["event"] = int(event) except ValueError: pass for k in d: if k in query_params: subqueries[query_params[k]] = d[k] return subqueries
def apply_filters(self, request, applicable_filters): """Apply the filters""" if 'location__contained' in applicable_filters: area = applicable_filters.pop('location__contained') poly = Polygon.from_bbox(area) applicable_filters['location__contained'] = poly return super(SampleResource, self).apply_filters(request, applicable_filters)
def test_inclusion_of_a_pole(self): self.rc.region_constraint = Polygon( ((-1, 0), (-1, 1), (1, 1), (1, 0), (-1, 0))) results = models.ExposureData.objects.get_asset_chunk( self.rc, "test", 0, 10) self.assertEqual(1, len(results)) self.assertEqual("test1", results[0].asset_ref) self.rc.region_constraint = Polygon( ((179, 10), (-179, 10), (-179, -10), (179, -10), (179, 10))) results = models.ExposureData.objects.get_asset_chunk( self.rc, "test", 0, 10) self.assertEqual(1, len(list(results))) self.assertEqual("test2", results[0].asset_ref)
def test_simple_inclusion(self): self.rc.region_constraint = Polygon( ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) results = models.ExposureData.objects.get_asset_chunk( self.rc, "test", 0, 10) self.assertEqual(1, len(list(results))) self.assertEqual("test1", results[0].asset_ref)
def _computed_domain(self): xmin, ymin, xmax, ymax = ( wrap_longitude_degrees(self.central_meridian_longitude_degrees - self.MAX_LONGITUDE_OFFSET), -90, wrap_longitude_degrees(self.central_meridian_longitude_degrees + self.MAX_LONGITUDE_OFFSET), 90, ) if xmin <= xmax: domain = Polygon.from_bbox((xmin, ymin, xmax, ymax)) domain.srid = WGS_84 return domain else: # cut at idealized international date line return MultiPolygon( Polygon.from_bbox((xmin, ymin, MAX_LONGITUDE_DEGREES, ymax)), Polygon.from_bbox((MIN_LONGITUDE_DEGREES, ymin, xmax, ymax)), srid=WGS_84, )
def _spatial_extent_(self): spatial_extent = self.archive_meta['spatial_extent'] min_x = float(spatial_extent['min_x']) max_x = float(spatial_extent['max_x']) min_y = float(spatial_extent['min_y']) max_y = float(spatial_extent['max_y']) p = Polygon(((min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y), (min_x, min_y)), srid=4326) return (p)
def create_parking_1(save=True): parking = Parking(name='Karlovo namesti', places_count=200, land_registry_number='100', street='Husova 5', city='Praha', polygon=Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)))) if save: parking.save() return parking
def cityracks_kml(request): bbox = request.REQUEST.get('bbox') if bbox: bbox = [float(n) for n in bbox.split(',')] assert len(bbox) == 4 geom = Polygon.from_bbox(bbox) cityracks = CityRack.objects.filter(the_geom__within=geom) else: cityracks = CityRack.objects.all() return render_to_kml('cityracks.kml', {'cityracks': cityracks})
def by_bbox(bbox_string): bbox = bbox_string.split(",") if len(bbox) != 4: raise InvalidSpatialParameterException("The bbox parameter must contain 4 items: xmin, ymin, xmax, ymax") try: bbox = map(float, bbox) except ValueError: raise InvalidSpatialParameterException("Items in the bbox parameter must be parseable as floats") return {"geom__intersects": Polygon.from_bbox(bbox)}
def get_geom(point, len_m): if type(point).__name__ == 'str': point = str_to_point(point) k_lat = 0.000009 k_long = 0.000013 top_lat = point[0] + (len_m * k_lat) top_long = point[1] - (len_m * k_long) bot_lat = point[0] - (len_m * k_lat) bot_long = point[1] + (len_m * k_long) bbox = (top_lat, top_long, bot_lat, bot_long) # print('get_geom',bbox) return Polygon.from_bbox(bbox)
def rack_search_kml(request): racks = Rack.objects.all() try: page_number = int(request.REQUEST.get('page_number', '1')) except ValueError: page_number = 1 try: page_size = int(request.REQUEST.get('page_size', sys.maxint)) except ValueError: page_size = sys.maxint status = request.GET.get('status') if status: racks = racks.filter(status=status) verified = request.GET.get('verified') if verified: racks = Rack.objects.filter_by_verified(verified, racks) # Get bounds from request. bbox = request.REQUEST.get('bbox') if bbox: bbox = [float(n) for n in bbox.split(',')] assert len(bbox) == 4 geom = Polygon.from_bbox(bbox) racks = racks.filter(location__within=geom) cb = request.GET.get('cb') boro = request.GET.get('boro') board = None borough = None if cb is not None: try: board = CommunityBoard.objects.get(gid=int(cb)) racks = racks.filter(location__within=board.the_geom) except (CommunityBoard.DoesNotExist, ValueError): board = None if board is None and boro is not None: try: borough = Borough.objects.get(gid=int(boro)) racks = racks.filter(location__within=borough.the_geom) except (CommunityBoard.DoesNotExist, ValueError): pass racks = racks.order_by(*DEFAULT_RACK_ORDER) paginator = Paginator(racks, page_size) page_number = min(page_number, paginator.num_pages) page = paginator.page(page_number) votes = Vote.objects.get_scores_in_bulk(racks) return render_to_kml("placemarkers.kml", {'racks' : racks, 'page': page, 'page_size': page_size, 'votes': votes, })
def get_queryset(self): queryset = MapData.objects.all() bbox = self.request.GET.get('bbox', None) if bbox: bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')]) queryset = filter_by_bounds(queryset, bbox) zoom = self.request.GET.get('zoom', None) if zoom: # We order by -length so that the geometries are in that # order when rendered by OpenLayers. This creates the # correct stacking order. queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length') return queryset.select_related('page')
def get_geom2(point, dist): if type(point).__name__ == 'str': point = str_to_point(point) mylat = point[0] mylon = point[1] dist = dist / 1000 lon1 = mylon - dist / abs(math.cos(math.radians(mylat)) * 111.0) lon2 = mylon + dist / abs(math.cos(math.radians(mylat)) * 111.0) lat1 = mylat + (dist / 111.0) lat2 = mylat - (dist / 111.0) bbox = (lat1, lon1, lat2, lon2) # print('get_geom2',bbox) return Polygon.from_bbox(bbox)
def get_queryset(self): queryset = MapData.objects.all() bbox = self.request.GET.get('bbox', None) if bbox: bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')]) queryset = filter_by_bounds(queryset, bbox) zoom = self.request.GET.get('zoom', None) if zoom: # We order by -length so that the geometries are in that # order when rendered by OpenLayers -- this creates the # correct stacking order. queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length') return queryset
def get_queryset(self): queryset = MapData.objects.all() bbox = self.request.GET.get("bbox", None) if bbox: bbox = Polygon.from_bbox([float(x) for x in bbox.split(",")]) queryset = filter_by_bounds(queryset, bbox) zoom = self.request.GET.get("zoom", None) if zoom: # We order by -length so that the geometries are in that # order when rendered by OpenLayers -- this creates the # correct stacking order. queryset = filter_by_zoom(queryset, int(zoom)).order_by("-length") return queryset
def by_bbox(bbox_string): bbox = bbox_string.split(',') if len(bbox) != 4: raise InvalidSpatialParameterException( 'The bbox parameter must contain 4 items: xmin, ymin, xmax, ymax') try: bbox = map(float, bbox) except ValueError: raise InvalidSpatialParameterException( 'Items in the bbox parameter must be parseable as floats') return {'geom__intersects': Polygon.from_bbox(bbox)}
def add_to_catalog (request , resource_form ,app_name , tags ,extent): resource = resource_form.save(commit=False) resource.app = App.objects.get(name= app_name) resource.created_by = request.user resource.last_updated_by = request.user resource.save() resource.set_tags(tags) bbox = (extent[0], extent[1], extent[2], extent[3]) resource.location_extent = Polygon.from_bbox(bbox) resource.save() resource_form.save_m2m() return resource
def get_queryset(self): queryset = MapData.objects.filter(region=self.get_region()) # XXX TODO TEMPORARY HACK queryset = queryset.exclude(page__pagetagset__tags__slug='zipcode') queryset = queryset.exclude(page__pagetagset__tags__slug='supervisorialdistrict') bbox = self.request.GET.get('bbox', None) if bbox: bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')]) queryset = filter_by_bounds(queryset, bbox) zoom = self.request.GET.get('zoom', None) if zoom: # We order by -length so that the geometries are in that # order when rendered by OpenLayers. This creates the # correct stacking order. queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length') return queryset.select_related('page')
def bounds_from_box(box): """Converts a `box` string parameter to a Polygon object. If given a Polygon, it is returned unchanged. :param box: (str) with the format latMin,longMin,latMax,longMax """ if isinstance(box, Polygon): return box coords = [float(coord) for coord in box.split(",")] assert len(coords) == 4 # Coordinates are submitted to the server as # latMin,longMin,latMax,longMax, but from_bbox wants its arguments in a # different order: return Polygon.from_bbox((coords[1], coords[0], coords[3], coords[2]))
def get_queryset(self): queryset = MapData.objects.filter(region=self.get_region()) # XXX TODO TEMPORARY HACK queryset = queryset.exclude(page__pagetagset__tags__slug='zipcode') queryset = queryset.exclude( page__pagetagset__tags__slug='supervisorialdistrict') bbox = self.request.GET.get('bbox', None) if bbox: bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')]) queryset = filter_by_bounds(queryset, bbox) zoom = self.request.GET.get('zoom', None) if zoom: # We order by -length so that the geometries are in that # order when rendered by OpenLayers. This creates the # correct stacking order. queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length') return queryset.select_related('page')
def build_proposal_query(d): subqueries = {} ids = build_attributes_query(d) or [] if "id" in d: ids = re.split(r"\s*,\s*", d["id"]) if ids: subqueries["pk__in"] = ids if "project" in d: if d["project"] == "null": subqueries["project__isnull"] = True elif d["project"] == "all": subqueries["project__isnull"] = False else: subqueries["project"] = d["project"] bounds = d.get("bounds") if bounds: coords = [float(coord) for coord in bounds.split(",")] bbox = Polygon.from_bbox(*coords, srid=97406) subqueries["location__within"] = bbox status = d.get("status", "active").lower() if status == "closed": subqueries["complete"] = True elif status == "active": subqueries["complete"] = False # If status is anything other than 'active' or 'closed', find all # proposals. event = d.get("event") if event: try: subqueries["event"] = int(event) except ValueError: pass for k in d: if k in query_params: subqueries[query_params[k]] = d[k] return Q(**subqueries)
def handle(self, *args, **options): verbosity = options.get('verbosity') file_path = options.get('file_path') area_type_name = options.get('area_type') name_column = options.get('name') encoding = options.get('encoding') srid = options.get('srid') do_intersect = options.get('intersect') bbox = Polygon.from_bbox(settings.SPATIAL_EXTENT) bbox.srid = settings.SRID ds = DataSource(file_path, encoding=encoding) count_error = 0 area_type, created = RestrictedAreaType.objects.get_or_create(name=area_type_name) if verbosity > 0: self.stdout.write("RestrictedArea Type's %s created" % area_type_name if created else "Get %s" % area_type_name) for layer in ds: for feat in layer: try: geom = feat.geom.geos if not isinstance(geom, Polygon) and not isinstance(geom, MultiPolygon): if verbosity > 0: self.stdout.write("%s's geometry is not a polygon" % feat.get(name_column)) break elif isinstance(geom, Polygon): geom = MultiPolygon(geom) self.check_srid(srid, geom) geom.dim = 2 if do_intersect and bbox.intersects(geom) or not do_intersect and geom.within(bbox): instance, created = RestrictedArea.objects.update_or_create(name=feat.get(name_column), area_type=area_type, defaults={ 'geom': geom}) if verbosity > 0: self.stdout.write("%s %s" % ('Created' if created else 'Updated', feat.get(name_column))) except OGRIndexError: if count_error == 0: self.stdout.write( "Name's attribute do not correspond with options\n" "Please, use --name to fix it.\n" "Fields in your file are : %s" % ', '.join(feat.fields)) count_error += 1
def edit_item(request, item_id): item_obj = Item.objects.get(id=item_id) if request.method == 'POST': item_json_obj = json.loads(request.POST['map-json']) item_obj.owner = request.user item_obj.name = item_json_obj['name'] item_obj.title = item_json_obj['title'] item_obj.url = item_json_obj['url'] item_obj.type = item_json_obj['type'] item_obj.type_keywords = ",".join(item_json_obj['typeKeywords']) item_obj.description = item_json_obj['description'] item_obj.tags = ",".join(item_json_obj['tags']) item_obj.snippet = item_json_obj['snippet'] item_obj.thumbnail = item_json_obj['thumbnail'] if item_json_obj['extent']: item_obj.extent = Polygon.from_bbox(item_json_obj['extent'][0] + item_json_obj['extent'][1]) item_obj.modified = datetime.datetime.today() item_obj.save() if 'text' in item_json_obj: item_data_obj = ItemData(item=item_obj, text=json.dumps(item_json_obj['text'])) item_data_obj.save() # TODO: handle array types in a better way. item_obj.type_keywords = item_obj.type_keywords.split(",") item_obj.tags = item_obj.tags.split(",") # TODO: handle single object instead of removing square brackets from the string. fields = [ 'name', 'title', 'url', 'type', 'type_keywords', 'description', 'tags', 'snippet', 'thumbnail', 'extent' ] item_json_obj = json.loads(ModelToJson().serialize( [item_obj], indent=True, fields=fields).strip("[]\n")) try: item_json_obj['text'] = json.loads( ItemData.objects.get(item_id=item_id).text) except: pass return render(request, 'content/edit_item.html', {'item_obj': json.dumps(item_json_obj, indent=4)})
def get_cars(**kwargs): manufacturer, created = CarModelManufacturer.objects.get_or_create( slug='slug', name='title') type, created = CarType.objects.get_or_create(type='type') fuel, created = Fuel.objects.get_or_create(title='title') color, created = CarColor.objects.get_or_create(color='blue') car_model, created = CarModel.objects.get_or_create( engine='engine', seats_count=1, storage_capacity=1, name='title', type=type, main_fuel=fuel, manufacturer=manufacturer) defaults = { 'active': True, 'manufacture_date': datetime.now(), 'model': car_model, 'color': color, 'home_subsidiary': get_subsidiary(), } defaults.update(**kwargs) try: car = Car.objects.get(registration_number='123123') except Car.DoesNotExist: car = Car.objects.create(registration_number='123123', **defaults) parking = Parking.objects.get_or_create(name='Test', places_count=200, land_registry_number='100', street='Test', city='Praha', polygon=Polygon( ((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)))) return car_model, car, parking
class Migration(migrations.Migration): dependencies = [ ('api', '0038_metadatacontact_is_validator'), ] operations = [ migrations.RunSQL( sql= "ALTER TABLE product ADD COLUMN geom2 geometry(MultiPolygon,2056);", reverse_sql="ALTER TABLE product DROP COLUMN geom2;"), migrations.RunSQL( sql= "CREATE INDEX IF NOT EXISTS product_geom2_id ON product USING gist (geom2)", reverse_sql="DROP INDEX product_geom2_id;"), migrations.RunSQL( sql="UPDATE product set geom2 = ST_Multi(geom);", reverse_sql= "UPDATE product set geom = (ST_DUMP(geom2)).geom::geometry(Polygon,2056);" ), migrations.RunSQL( sql="ALTER TABLE product DROP COLUMN geom;", reverse_sql= "ALTER TABLE product ADD COLUMN geom geometry(Polygon,2056);"), migrations.RunSQL( sql="ALTER TABLE product RENAME COLUMN geom2 TO geom;", reverse_sql="ALTER TABLE product RENAME COLUMN geom TO geom2;", state_operations=[ migrations.AlterField( model_name='product', name='geom', field=MultiPolygonField(default=MultiPolygon( Polygon.from_bbox( (2519900, 1186430, 2578200, 1227030))), srid=2056, verbose_name='geom'), ), ], ), ]
def build_proposal_query(d): subqueries = {} ids = build_attributes_query(d) or [] pids = d.get("id") if pids: ids = re.split(r"\s*,\s*", pids) if ids: subqueries["pk__in"] = ids bounds = d.get("bounds") if bounds: coords = [float(coord) for coord in bounds.split(",")] bbox = Polygon.from_bbox(*coords, srid=97406) subqueries["location__within"] = bbox status = d.get("status", "active").lower() if status == "closed": subqueries["complete"] = True elif status == "active": subqueries["complete"] = False # If status is anything other than 'active' or 'closed', find all # proposals. event = d.get("event") if event: try: subqueries["event"] = int(event) except ValueError as verr: pass for k in d: if k in query_params: subqueries[query_params[k]] = d[k] return Q(**subqueries)
def setupTreemapEnv(): settings.GEOSERVER_GEO_LAYER = "" settings.GEOSERVER_GEO_STYLE = "" settings.GEOSERVER_URL = "" def local_render_to_response(*args, **kwargs): from django.template import loader, RequestContext from django.http import HttpResponse httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} hr = HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) if hasattr(args[1], 'dicts'): hr.request_context = args[1].dicts return hr django.shortcuts.render_to_response = local_render_to_response r1 = ReputationAction(name="edit verified", description="blah") r2 = ReputationAction(name="edit tree", description="blah") r3 = ReputationAction(name="Administrative Action", description="blah") r4 = ReputationAction(name="add tree", description="blah") r5 = ReputationAction(name="edit plot", description="blah") r6 = ReputationAction(name="add plot", description="blah") r7 = ReputationAction(name="add stewardship", description="blah") r8 = ReputationAction(name="remove stewardship", description="blah") for r in [r1, r2, r3, r4, r5, r6, r7, r8]: r.save() bv = BenefitValues(co2=0.02, pm10=9.41, area="InlandValleys", electricity=0.1166, voc=4.69, ozone=5.0032, natural_gas=1.25278, nox=12.79, stormwater=0.0078, sox=3.72, bvoc=4.96) bv.save() dbh = "[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]" dbh2 = "[2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]" rsrc1 = Resource(meta_species="BDM OTHER", region="NoEastXXX") rsrc2 = Resource(meta_species="BDL OTHER", region="NoEastXXX") rsrc1.save() rsrc2.save() u = User.objects.filter(username="******") if u: u = u[0] else: u = User.objects.create_user("jim", "*****@*****.**", "jim") u.is_staff = True u.is_superuser = True u.save() up = UserProfile(user=u) up.save() u.reputation = Reputation(user=u) u.reputation.save() amy_filter_result = User.objects.filter(username="******") if not amy_filter_result: amy = User.objects.create_user("amy", "*****@*****.**", "amy") else: amy = amy_filter_result[0] amy.is_staff = False amy.is_superuser = False amy.save() amy_profile = UserProfile(user=amy) amy_profile.save() amy.reputation = Reputation(user=amy) amy.reputation.save() olivia_filter_result = User.objects.filter(username="******") if not amy_filter_result: olivia = User.objects.create_user("olivia", "*****@*****.**", "olivia") else: olivia = olivia_filter_result[0] olivia.is_staff = False olivia.is_superuser = False olivia.save() olivia_profile = UserProfile(user=olivia) olivia_profile.save() olivia.reputation = Reputation(user=olivia) olivia.reputation.save() n1geom = MultiPolygon( Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0)))) n2geom = MultiPolygon( Polygon(((0, 101), (101, 101), (101, 200), (0, 200), (0, 101)))) n1 = Neighborhood(name="n1", region_id=2, city="c1", state="PA", county="PAC", geometry=n1geom) n2 = Neighborhood(name="n2", region_id=2, city="c2", state="NY", county="NYC", geometry=n2geom) n1.save() n2.save() z1geom = MultiPolygon( Polygon(((0, 0), (100, 0), (100, 100), (0, 100), (0, 0)))) z2geom = MultiPolygon( Polygon(((0, 100), (100, 100), (100, 200), (0, 200), (0, 100)))) z1 = ZipCode(zip="19107", geometry=z1geom) z2 = ZipCode(zip="10001", geometry=z2geom) z1.save() z2.save() exgeom1 = MultiPolygon( Polygon(((0, 0), (25, 0), (25, 25), (0, 25), (0, 0)))) ex1 = ExclusionMask(geometry=exgeom1, type="building") ex1.save() agn1 = AggregateNeighborhood(annual_stormwater_management=0.0, annual_electricity_conserved=0.0, annual_energy_conserved=0.0, annual_natural_gas_conserved=0.0, annual_air_quality_improvement=0.0, annual_co2_sequestered=0.0, annual_co2_avoided=0.0, annual_co2_reduced=0.0, total_co2_stored=0.0, annual_ozone=0.0, annual_nox=0.0, annual_pm10=0.0, annual_sox=0.0, annual_voc=0.0, annual_bvoc=0.0, total_trees=0, total_plots=0, location=n1) agn2 = AggregateNeighborhood(annual_stormwater_management=0.0, annual_electricity_conserved=0.0, annual_energy_conserved=0.0, annual_natural_gas_conserved=0.0, annual_air_quality_improvement=0.0, annual_co2_sequestered=0.0, annual_co2_avoided=0.0, annual_co2_reduced=0.0, total_co2_stored=0.0, annual_ozone=0.0, annual_nox=0.0, annual_pm10=0.0, annual_sox=0.0, annual_voc=0.0, annual_bvoc=0.0, total_trees=0, total_plots=0, location=n2) agn1.save() agn2.save() s1 = Species(symbol="s1", genus="testus1", species="specieius1", cultivar_name='', family='', alternate_symbol='a1') s2 = Species(symbol="s2", genus="testus2", species="specieius2", cultivar_name='', family='', alternate_symbol='a2') s3 = Species(symbol="s3", genus="testus2", species="specieius3", cultivar_name='', family='', alternate_symbol='a3') s1.native_status = 'True' s1.fall_conspicuous = True s1.flower_conspicuous = True s1.palatable_human = True s2.native_status = 'True' s2.fall_conspicuous = False s2.flower_conspicuous = True s2.palatable_human = False s2.wildlife_value = True s3.wildlife_value = True s1.save() s2.save() s3.save() s1.resource.add(rsrc1) s2.resource.add(rsrc2) s3.resource.add(rsrc2) ie = ImportEvent(file_name='site_add') ie.save()
def make_polybbox(self,bbox): return Polygon.from_bbox(bbox)
def handle(self, **options): '''This method takes a given shape names and queries the usgs api for available scenes. Using two api clients for the usgs and espa we query for a given shape and create an order to download the landsat scenes for a specific temporal window. ''' usgs_client = UsgsApi() usgs_client.login() start_date = options['start_date'][0] end_date = options['end_date'][0] landsat = int(options['landsat'][0]) shape_name = options['shape'][0] cloud_cover = options['max_cloud_cover'] espa_client = EspaApi() logger.info(shape_name) try: shape_object = Country.objects.get(name=shape_name) logger.info('Country %s was loaded.' % shape_name) except: try: shape_object = Region.objects.get(name=shape_name) logger.info('Region %s was loaded.' % shape_name) except: shape_object = None if shape_object: extent = shape_object.the_geom.extent if landsat == 8: collection_usgs = 'LANDSAT_8_C1' collection_espa = 'olitirs8_collection' collection_regex = '^lc08_{1}\\w{4}_{1}[0-9]{6}_{1}[0-9]{8}_{1}[0-9]{8}_{1}[0-9]{2}_{1}\\w{2}$' elif landsat == 7: collection_usgs = 'LANDSAT_ETM_C1' collection_espa = 'etm7_collection' collection_regex = '^le07_{1}\\w{4}_{1}[0-9]{6}_{1}[0-9]{8}_{1}[0-9]{8}_{1}[0-9]{2}_{1}\\w{2}$' elif landsat == 5: collection_usgs = 'LANDSAT_TM_C1' collection_espa = 'tm5_collection' collection_regex = '^lt05_{1}\\w{4}_{1}[0-9]{6}_{1}[0-9]{8}_{1}[0-9]{8}_{1}[0-9]{2}_{1}\\w{2}$' data = usgs_client.search(extent, collection_usgs, start_date=start_date, end_date=end_date, max_cloud_cover=cloud_cover).get('data') products = ['sr', 'pixel_qa'] interest = [] if data: results = data.get('results') if results: for scene in results: coords = tuple( point_from_object(scene.get(coord)) for coord in [ 'lowerLeftCoordinate', 'upperLeftCoordinate', 'upperRightCoordinate', 'lowerRightCoordinate', 'lowerLeftCoordinate' ]) scene_extent = Polygon(coords) entity_id = scene.get('displayId') # we use the same regular expression that espa uses to filter the names that are valid; otherwise, the order throws an error if scene_extent.intersects( shape_object.the_geom) and re.match( collection_regex, entity_id.lower()): interest.append(entity_id) footprint, _ = Footprint.objects.get_or_create( name=entity_id, the_geom=scene_extent) print(json.dumps(interest, indent=4)) data = espa_client.order(collection_espa, interest, products) if data.get('status') == 'ordered': logger.info('The order was posted with id: %s' % data.get('orderid')) order = Order(user=espa_client.username, order_id=data.get('orderid'), downloaded=False) order.save() else: logger.info(json.dumps(data, indent=4)) else: logger.info( 'No shape with the name %s was found in the database.' % shape_name)
def convert2pgsql(self) -> List[PlanetOsmPolygon]: # https://wiki.openstreetmap.org/wiki/Relation:multipolygon/Algorithm previous_timestamp: date = self.timestamp rel: PlanetOsmRels multipolygons: List[PlanetOsmPolygon] = [] for rel in self.rels: if (not rel.visible or not rel.outer_members or not rel.inner_members or not rel.tags): if rel.timestamp: previous_timestamp = rel.timestamp continue if rel.rel_type != "multipolygon" and rel.rel_type != "boundary": continue ways: Dict[int, PlanetOsmWays] = {} way: PlanetOsmWays for way in PlanetOsmWays.objects.filter( osm_id__in=rel.outer_members, visible=True).order_by("osm_id", "-version"): if not way.way or not way.way.closed: # todo combine not closed ways continue if way.osm_id in ways: if way.timestamp <= ways[way.osm_id].timestamp: ways[way.osm_id] = way else: ways[way.osm_id] = way for way in PlanetOsmWays.objects.filter( osm_id__in=rel.inner_members, visible=True).order_by("osm_id", "-version"): if not way.way or not way.way.closed: # todo combine not closed ways continue if way.osm_id in ways: if way.timestamp <= ways[way.osm_id].timestamp: ways[way.osm_id] = way else: ways[way.osm_id] = way polygons: List[Polygon] = [] for osm_id in rel.outer_members: if osm_id in ways: polygons.append(Polygon(ways[osm_id].way.coords)) for osm_id in rel.inner_members: if osm_id in ways: polygons.append(Polygon(ways[osm_id].way.coords)) multipolygon: MultiPolygon = MultiPolygon(polygons) polygon: PlanetOsmPolygon = PlanetOsmPolygon( osm_id=rel.osm_id, version=rel.version, way=GEOSGeometry(multipolygon.wkt), valid_since=rel.timestamp, valid_until=previous_timestamp, tags=rel.tags, ) polygon = fill_osm_object(osm_object=polygon) multipolygons.append(polygon) previous_timestamp = rel.timestamp self.rels.clear() self.osm_id = None return multipolygons
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom): # start drawing each block pil_map = Image.new("RGBA", (width, height), (255,255,255, 0)) pil_draw = ImageDraw.Draw(pil_map) # return empty images if zoom < 11: return pil_map # first, figure out the bounding box of the tile we're rendering nw = self.layer.projection.projLocation(ModestMaps.Core.Point(xmin, ymin)) se = self.layer.projection.projLocation(ModestMaps.Core.Point(xmax, ymax)) max_lat = max(nw.lat, se.lat) min_lat = min(nw.lat, se.lat) max_lon = max(nw.lon, se.lon) min_lon = min(nw.lon, se.lon) # Converting polygon to OSGB36 in order to compare with the ones we have in # the database shp = ShpParser() min_p = shp.convert_point_to_OSGB36(min_lat, min_lon) max_p = shp.convert_point_to_OSGB36(max_lat, max_lon) bbox = Polygon.from_bbox((min_p[0], min_p[1], max_p[0], max_p[1])) # this obj is used to translate between lat/lon and pixel space bound1 = ModestMaps.Geo.Location(min_lat, min_lon) bound2 = ModestMaps.Geo.Location(max_lat, max_lon) mmap = ModestMaps.mapByExtentZoom(self.provider, bound1, bound2, zoom) neighbourhoods = False polys = None max_x = None min_x = None try: # If zoom < 15 we draw postcode polygons, otherwise neighbourhoods if zoom < 15 or self.type == "None": polys = Neighbourhood.objects.filter(poly__intersects=bbox) neighbourhoods = True else: polys = Postcode.objects.filter(poly__intersects=bbox) print "Painting", polys.count(), "blocks" # Have to find the city where the polygons belong in _city = None if self.type != "None": for poly in polys: if _city is not None: break if poly.poly and isinstance(poly.poly, geos.MultiPolygon): for inside_poly in poly.poly: if _city is None: # Find the city if we haven't found it yet cities = Council.objects.filter(poly__intersects=inside_poly) if len(cities) > 0: _city = cities[0].convexhull.name break else: # Probably unneeded as eventually we only have Multipolygons in our db if _city is None: # Find the city if we haven't found it yet cities = Council.objects.filter(poly__intersects=inside_poly) if len(cities) > 0: _city = cities[0].convexhull.name break print "City:", _city if len(polys) > 0 and self.type != "None": if neighbourhoods: _name = _city+"_neighbourhood_max_"+self.type max_x = float(Statistics.objects.filter(name=_name).all()[0].stat) _name = _city+"_neighbourhood_min_"+self.type min_x = float(Statistics.objects.filter(name=_name).all()[0].stat) else: _name = _city+"_postcode_max_"+self.type max_x = float(Statistics.objects.filter(name=_name).all()[0].stat) _name = _city+"_postcode_min_"+self.type min_x = float(Statistics.objects.filter(name=_name).all()[0].stat) print "max:", max_x, "min:", min_x # For all the polygons we've retrieved from the database (in OSGB36 format) for poly in polys: _city = None if poly.poly and isinstance(poly.poly, geos.MultiPolygon): for inside_poly in poly.poly: if _city is None: # Find the city if we haven't found it yet cities = Council.objects.filter(poly__intersects=inside_poly) if len(cities) > 0: _city = cities[0].convexhull.name self._paint_poly(inside_poly, shp, mmap, pil_draw, _city, max_x, min_x, neighbourhoods) else: # Probably unneeded as eventually we only have Multipolygons in our db if _city is None: # Find the city if we haven't found it yet cities = Council.objects.filter(poly__intersects=inside_poly) if len(cities) > 0: _city = cities[0].convexhull.name self._paint_poly(poly.poly, shp, mmap, pil_draw, _city, max_x, min_x, neighbourhoods) except Exception, err: print err
def query_args_bbox(bbox_string): bbox = bbox_string.split(',') return { 'geom__intersects': Polygon.from_bbox(bbox) }
def publish(self): if self.portal_item: item_obj = self.portal_item item_data_obj = ItemData.objects.get(item=item_obj) else: item_obj = Item() item_data_obj = ItemData() # save portal item item_obj.owner = self.geonode_map.owner item_obj.name = self.geonode_map.title.replace(" ", "_") item_obj.title = self.geonode_map.title item_obj.url = None item_obj.type = "Web Map" item_obj.type_keywords = ",".join([ "ArcGIS Online", "Explorer Web Map", "Map", "Online Map", "Web Map" ]) item_obj.description = self.geonode_map.title item_obj.tags = ",".join([ 'map', ]) # todo: get tags from geonode item_obj.snippet = 'snippet' # todo item_obj.thumbnail = self.geonode_map.thumbnail_url m = self.geonode_map bbox = [m.bbox_x0, m.bbox_y0, m.bbox_x1, m.bbox_y1] item_obj.extent = Polygon.from_bbox(bbox) item_obj.save() # save item data item_data_json = json.loads(render_to_string(ITEM_DATA_JSON_TPL, {})) op_layers = [] site_url = settings.SITEURL if site_url.endswith("/"): site_url = site_url[:-1] wms_url = settings.OGC_SERVER["default"]["PUBLIC_LOCATION"] if wms_url.endswith("/"): wms_url += "wms" else: wms_url += "/wms" wms_layers = [] # [{ # "name": layergroup_name, # "title": layergroup_name # # }] for layer_obj in self.geonode_map.layer_set.all().exclude( group="background"): try: featurelayer = FeatureLayer.objects.get( geonode_layer__typename=layer_obj.name) fields = [] for f in featurelayer.fields_defs: fields.append({ "fieldName": f["name"], "label": f["alias"], "isEditable": f["editable"], "tooltip": "", "visible": True, "format": None, "stringFieldOption": "textbox" # TODO chanege according to field type }) layer_params_obj = json.loads(layer_obj.layer_params) title = layer_params_obj.get("title", layer_obj.layer_title) op_layers.append({ "id": "layer_%d" % layer_obj.id, "layerType": "ArcGISFeatureLayer", "url": site_url + featurelayer.meta_page_url, "visibility": True, "opacity": 0, "mode": 1, "title": title, "popupInfo": { "title": title, "fieldInfos": fields, "description": None, "showAttachments": True, "mediaInfos": [] } }) wms_layers.append({"name": layer_obj.name, "title": title}) except: pass op_layers.insert( 0, { "id": "wms", "title": "WMS", "url": wms_url, "visibility": True, "visibleLayers": [layer['name'] for layer in wms_layers], "opacity": 1, "type": "WMS", "layerType": "WMS", "version": "1.1.1", "mapUrl": wms_url, "layers": wms_layers, "spatialReferences": [ 3857, 2154, 23030, 23031, 23032, 27561, 27562, 27563, 27564, 27571, 27572, 27573, 27574, 3035, 3942, 3948, 4171, 4258, 4326, 900913 ], "extent": [[ float(self.geonode_map.bbox_x0), float(self.geonode_map.bbox_y0) ], [ float(self.geonode_map.bbox_x1), float(self.geonode_map.bbox_y1) ]], "copyright": "" }) item_data_json["operationalLayers"] = op_layers item_data_obj.item = item_obj item_data_obj.text = json.dumps(item_data_json) item_data_obj.save() # save map self.portal_item = item_obj self.edited = False self.save()
def hydrate_location_extent(self, bundle): if 'location_extent' in bundle.data: e = bundle.data['location_extent'] bbox = (e[0],e[1],e[2],e[3]) bundle.obj.location_extent = Polygon.from_bbox(bbox) return bundle