def setUpTestData(cls): """ Set base data for all test case """ cls.user_1 = UserFactory() cls.user_admin = UserAdminFactory() cls.status_1 = StatusFactory() cls.status_2 = StatusFactory() cls.grid_1 = KmGridFactory() cls.centroid_1 = KmGrid.objects.filter(id=cls.grid_1.id).\ annotate(centroid=Centroid('geometry'))[0].centroid cls.report_1_json = { "location": { "type": "Point", "coordinates": [cls.centroid_1.x, cls.centroid_1.y] }, "status": cls.status_1.id, "user": cls.user_1.id, } cls.grid_2 = KmGridFactory() cls.centroid_2 = KmGrid.objects.filter(id=cls.grid_2.id).\ annotate(centroid=Centroid('geometry'))[0].centroid cls.report_2_json = { "location": { "type": "Point", "coordinates": [cls.centroid_2.x, cls.centroid_2.y] }, "status": cls.status_2.id, "user": cls.user_1.id, } cls.report_3 = ReportFactory()
def recalculate_region_cache(apps, schema_editor): Region = apps.get_model('geo', 'Region') GeoArea = apps.get_model('geo', 'GeoArea') Region.objects.update(centroid=models.Subquery( GeoArea.objects.filter(admin_level__region=models.OuterRef('pk')). values('admin_level__region').order_by().annotate(centroid=Centroid( PgUnion(Centroid('polygons'))), ).values('centroid')[:1], output_field=models.PointField(), ))
def setUpTestData(cls): """ Set base data for all test case """ cls.user_admin = UserAdminFactory() cls.grid_1 = KmGridFactory() cls.centroid_1 = KmGrid.objects.filter(id=cls.grid_1.id).\ annotate(centroid=Centroid('geometry'))[0].centroid cls.grid_2 = KmGridFactory() cls.centroid_2 = KmGrid.objects.filter(id=cls.grid_2.id).\ annotate(centroid=Centroid('geometry'))[0].centroid
def create_travel_distances(new=False): # run to create travel details for the divisions if new: TravelDetails.objects.all().delete() for division_a in CountryDivision.objects.all(): for division_b in CountryDivision.objects.all().annotate( _distance=Distance(Centroid('geom'), Centroid( division_a.geom))): d = ureg.Quantity(division_b._distance.mi * ureg.mi) td = TravelDetails(distance=d, destination=division_a) td.save() division_b.distances.add(td) division_b.save() print(td)
def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context.update(self.get_queryset().aggregate( count=Count('spatial_id', distinct=True), coordinates=ArrayAgg(AsGeoJSON(Centroid('footprint'))), instrumentation_count=Count( 'instrumentation', distinct=True, filter=Q(instrumentation__isnull=False), ), acquisition_date__min=Min( 'acquisition_date', filter=Q(acquisition_date__isnull=False)), acquisition_date__max=Max( 'acquisition_date', filter=Q(acquisition_date__isnull=False)), extents=Extent('outline'), )) context['coordinates'] = '[' + ','.join(context['coordinates']) + ']' extents = context['extents'] or [None] * 4 context['extents'] = json.dumps({ 'xmin': extents[0], 'ymin': extents[1], 'xmax': extents[2], 'ymax': extents[3], }) return context
def update_centroid(self): clone = self._chain() for each in clone.annotate(cent=Centroid('geom')): each.point = each.cent each.latitude = each.point.y each.longitude = each.point.x each.geoname, __ = GeoName.objects.get_or_create( lat=each.point.y, lng=each.point.x, ) each.save()
def select_aoj_request(request): # function for select by location and send data to map aoj_code = json.loads(request.GET["code"]) # get AOJ code from html aoj = Aoj_C2.objects.all().filter(code=aoj_code) # AOJ queryset from Models aoj_poly = aoj[0].geom # aoj_poly is Geometry Dataset tr = Transformer_C2.objects.all().filter(geom__within = aoj_poly) # Transformer in AOJ Polygon # built AOJ GeoJSON object and add centroid in fields cent. qs = Aoj_C2.objects.all().filter(code=aoj_code).annotate(cent=AsGeoJSON(Centroid('geom'))) for i in qs.values(): print(json.loads(i.get("cent")).get("coordinates")) centroid_aoj = json.loads(i.get("cent")).get("coordinates") res = serialize( # pack GeoJSON in res variable. 'geojson', Aoj_C2.objects.all().filter(code=aoj_code), fields=('geom', ), ) tr_geojson = serialize( 'geojson', Transformer_C2.objects.all().filter(geom__within = aoj_poly), fields=('geom', ), ) result = [] result_dict = {} for i in tr : json_obj = json.loads(i.geom.json) # Edit JSON Schema if you want addition more fields. result_dict.update({"peano": i.facilityid, "ratekva": i.ratekva, "gistag" : i.tag, "feederID": i.feederid, "phase" : i.phasedesig, "name" : i.name, "flag" : i.flag, "impact" : i.impact, "baseload" : i.loadProfile_base, "numberOfCustomer" : i.numberOfCustomer, "evload" : i.loadProfile_ev, "coordinate": json_obj["coordinates"]}) result.append(result_dict) result_dict = {} # data = json.loads(tr_geojson) # with open("./transformer_geojson.json", 'w') as f: # json.dump(data, f) return JsonResponse({ "data": res, \ "coordinate_cent" : centroid_aoj, \ "point": json.dumps(result) })
def setUpTestData(cls): """ Set base data for all test case """ cls.user_admin = UserAdminFactory() cls.valid_file_path = f'{settings.BASE_DIR}/../example/grid.geojson' import_grid_from_geojson(cls.valid_file_path) generate_grid_score() cls.grid_1 = KmGridScore.objects.all().first() cls.centroid_1 = KmGridScore.objects.filter(id=cls.grid_1.id).\ annotate(centroid=Centroid('geometry'))[0].centroid cls.grid_2 = KmGridScore.objects.all().last() cls.centroid_2 = KmGridScore.objects.filter(id=cls.grid_2.id).\ annotate(centroid=Centroid('geometry'))[0].centroid cls.bbox = [ 107.42946624755861, -6.827265476865927, 107.82085418701173, -6.990182112864024 ]
def select_aoj_request(request): aoj_code = json.loads(request.GET["code"]) tr_c2 = os.path.abspath( os.path.join(os.path.dirname(transformer_model.__file__), 'data', 'DS_Transformer_C2_Pro.shp')) aoj = Aoj_C2.objects.all().filter(code=aoj_code) aoj_poly = aoj[0].geom print(type(aoj_poly)) tr = Transformer_C2.objects.all().filter(geom__within=aoj_poly) print(len(tr)) qs = Aoj_C2.objects.all().filter(code=aoj_code).annotate( cent=AsGeoJSON(Centroid('geom'))) for i in qs.values(): print(json.loads(i.get("cent")).get("coordinates")) centroid_aoj = json.loads(i.get("cent")).get("coordinates") res = serialize( 'geojson', Aoj_C2.objects.all().filter(code=aoj_code), fields=('geom', ), ) result = [] result_dict = {} for i in tr: # point_tr.append(i.geom.geojson) # pea_no.append(i.facilityid) # print(type(i.geom.json)) json_obj = json.loads(i.geom.json) result_dict.update({ "peano": i.facilityid, "ratekva": i.ratekva, "gistag": i.tag, "feederID": i.feederid, "phase": i.phasedesig, "name": i.name, "flag": i.flag, "impact": i.impact, "baseload": i.loadProfile_base, "evload": i.loadProfile_ev, "coordinate": json_obj["coordinates"] }) result.append(result_dict) result_dict = {} print(result) return JsonResponse({"data": res, "coordinate_cent" : centroid_aoj, \ "point": json.dumps(result)})
def handle(self, *args, **options): states = State.objects.all().annotate( centroid=AsGeoJSON(Centroid('geometry')), ) for state in states: center_data = json.loads(state.centroid) lng = center_data['coordinates'][0] lat = center_data['coordinates'][1] state.center_lng = lng state.center_lat = lat state.save()
def get_country_centroid_as_geojson(name): """ Gets a country centroid as GeoJSON hint: nested geofunction calls """ if (name[0].islower()): name = get_capitalized_country_name(name) try: country = Country.objects.annotate( json=AsGeoJSON(Centroid('mpoly'))).get(name=name).json return (country) except Country.DoesNotExist as error: raise Country.DoesNotExist(error)
def save(self, *args, **kwargs): if file_exists(self.geojson_file): with self.geojson_file.open(mode='r') as file_handler: borders = file_handler.read() self.borders = borders # if self.geojson_file and file_exists(self.geojson_file): # self.geojson_file.open(mode='rb') if self.borders: regions = Region.objects.annotate(center=Centroid('borders')) self.map_center = regions.get(pk=self.pk).center super().save(*args, **kwargs)
def calc_cache(self, save=True): self.geo_options = [ { 'label': '{} / {}'.format(geo_area.admin_level.title, geo_area.title), 'title': geo_area.title, 'key': str(geo_area.id), 'admin_level': geo_area.admin_level.level, 'admin_level_title': geo_area.admin_level.title, 'region': self.id, 'region_title': self.title, 'parent': geo_area.parent.id if geo_area.parent else None, } for geo_area in GeoArea.objects.prefetch_related( 'admin_level', ).filter( admin_level__region=self ).order_by('admin_level__level').distinct() ] # Calculate region centroid self.centroid = GeoArea.objects\ .filter(admin_level__region=self)\ .aggregate(centroid=Centroid(PgUnion(Centroid('polygons'))))['centroid'] if save: self.save()
def space_centroid(request, space_id): space_qs = BuildingFloorSpace.objects.filter(pk=space_id) if space_qs: att = space_qs.values()[0] if att['multi_poly']: att['multi_poly'] = None centroid_res = BuildingFloorSpace.objects.annotate( json=AsGeoJSON(Centroid('multi_poly'))).get(pk=space_id).json res = Feature(geometry=json.loads(centroid_res), properties=att) return Response(res) else: return Response({ 'error': 'Sorry we did not find any record in our database matching your id = ' + str(space_id) })
def setUp(self): self.report_data = ReportFactory() self.geometry = self.report_data.grid.geometry self.centroid = KmGrid.objects.annotate(centroid=Centroid('geometry'))[0].centroid self.report_data_json = { "grid": self.report_data.grid.id, "status": self.report_data.status.id, "user": self.report_data.user.id, } self.report_create_data_json = { "location": { "type": "Point", "coordinates": [ self.centroid.x, self.centroid.y ] }, "status": self.report_data.status.id, "user": self.report_data.user.id, }
def set_centroids(): for pct in PCT.objects.filter(boundary__isnull=False).annotate( centroid_annotation=Centroid("boundary") ): pct.centroid = pct.centroid_annotation pct.save()
def get_queryset(self): ''' kwarg: zipcode query_params: - med_id: MedicationName id - formulations: list of Medication ids - provider_type: list of ProviderType ids - provider_category: list of ProviderCategory ids - drug_type: list of 1 character str, for drug_type in Medication - state_id: int of a state obj, used when more than one zipcode ''' med_id = self.request.query_params.get('med_id') state_id = self.request.query_params.get('state_id') provider_category_filters = self.request.query_params.getlist( 'provider_categories[]', []) provider_type_filters = self.request.query_params.getlist( 'provider_types[]', []) user = self.request.user zipcode = self.kwargs.get('zipcode') # check permission state_id, zipcode = force_user_state_id_and_zipcode( user, state_id, zipcode) try: int(med_id) except (ValueError, TypeError): return ZipCode.objects.filter(zipcode=zipcode).annotate( centroid=AsGeoJSON(Centroid('geometry')), ) provider_medication_ids = get_provider_medication_id( self.request.query_params, ) if state_id: zipcode_qs = ZipCode.objects.filter( zipcode=zipcode, state=state_id, ) else: zipcode_qs = ZipCode.objects.filter(zipcode=zipcode) zipcode_qs = zipcode_qs.annotate( active_provider_count=Count( 'providers__id', filter=Q(providers__active=True, providers__category__id__isnull=False, providers__type__id__isnull=False, providers__provider_medication__id__in= provider_medication_ids), distinct=True), total_provider_count=Count('providers__id', distinct=True), medication_levels=ArrayAgg( 'providers__provider_medication__level', filter=Q(providers__provider_medication__id__in= provider_medication_ids # noqa )), centroid=AsGeoJSON(Centroid('geometry')), ) return zipcode_qs