def test_length(self): """ Test the `Length` function. """ # Reference query (should use `length_spheroid`). # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563, # AUTHORITY["EPSG","7030"]]'); len_m1 = 473504.769553813 len_m2 = 4617.668 if connection.features.supports_length_geodetic: qs = Interstate.objects.annotate(length=Length('path')) tol = 2 if oracle else 3 self.assertAlmostEqual(len_m1, qs[0].length.m, tol) # TODO: test with spheroid argument (True and False) else: # Does not support geodetic coordinate systems. with self.assertRaises(NotImplementedError): list(Interstate.objects.annotate(length=Length('path'))) # Now doing length on a projected coordinate system. i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get( name='I-10') self.assertAlmostEqual(len_m2, i10.length.m, 2) self.assertTrue( SouthTexasInterstate.objects.annotate( length=Length('path')).filter(length__gt=4000).exists())
def test_length(self): """ Testing Length() function on 3D fields. """ # ST_Length_Spheroid Z-aware, and thus does not need to use # a separate function internally. # `SELECT ST_Length_Spheroid(line, 'SPHEROID["GRS 1980",6378137,298.257222101]') # FROM geo3d_interstate[2d|3d];` self._load_interstate_data() tol = 3 ref_length_2d = 4368.1721949481 ref_length_3d = 4368.62547052088 inter2d = Interstate2D.objects.annotate(length=Length("line")).get( name="I-45") self.assertAlmostEqual(ref_length_2d, inter2d.length.m, tol) inter3d = Interstate3D.objects.annotate(length=Length("line")).get( name="I-45") self.assertAlmostEqual(ref_length_3d, inter3d.length.m, tol) # Making sure `ST_Length3D` is used on for a projected # and 3D model rather than `ST_Length`. # `SELECT ST_Length(line) FROM geo3d_interstateproj2d;` ref_length_2d = 4367.71564892392 # `SELECT ST_Length3D(line) FROM geo3d_interstateproj3d;` ref_length_3d = 4368.16897234101 inter2d = InterstateProj2D.objects.annotate(length=Length("line")).get( name="I-45") self.assertAlmostEqual(ref_length_2d, inter2d.length.m, tol) inter3d = InterstateProj3D.objects.annotate(length=Length("line")).get( name="I-45") self.assertAlmostEqual(ref_length_3d, inter3d.length.m, tol)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['road_count'] = Roads.objects.all().count() context['contractors_count'] = Development.objects.values( "contractor").annotate(Count("contractor", distinct=True)).count() context['contractors'] = Development.objects.values( "contractor").annotate(contracts_count=Count("contractor")) context['status'] = Development.objects.values("status").annotate( status_count=Count("status")) context['road_authorities'] = Roads.objects.values( "authority").annotate(material_count=Count("authority")) context['roads_length'] = Roads.objects.values("geom").annotate( length=Length("geom")).values("length") context['total_length'] = reduce( (lambda x, y: x + y), [r['length'].km for r in context["roads_length"]]) context['conct_sum'] = Development.objects.exclude( conct_sum__isnull=True).values("conct_sum") print(context['conct_sum']) context['total_cost'] = reduce( (lambda x, y: x + y), [r['conct_sum'] for r in context["conct_sum"]]) print(context['total_cost']) return context
def StatsView(request): streets = Street.objects.all() s = Segment.objects.all().distinct('district', 'street') values = [[i.name, s.filter(district=i.id).count()] for i in DictDistricts.objects.all()] split_by = 25 min_len = 0 max_len = 5000 step = (max_len - min_len) / split_by q = Segment.objects.values('street').annotate(leng=Sum(Length('geom'))) ret = [[ "≤ " + str(int(min_len + step * (i + 1))), q.filter(leng__gte=min_len + step * i).filter(leng__lt=min_len + step * (i + 1)).count() ] for i in range(split_by)] street_count = Street.objects.count() segment_count = Segment.objects.count() return render( request, 'main/stats.html', { 'values': values, 'len_stat': ret, 'street_count': street_count, 'segment_count': segment_count, })
def length(self): """ Calculate the total length (in m) of this line """ annotated_self = self.__class__.objects.annotate( length=Length('geo')).get(pk=self.pk) return annotated_self.length.m
def handle(self, *args, **options): print("Calculando country codes") b = kings aas = AdministrativeArea.objects.filter(depth=1) for aa in aas: cc = next(v['country_code'] for k, v in kings.items() if v['id'] == aa.osm_id) print(f' > {aa.osm_type} {aa.osm_id} {aa.name}') print(' - Lineas: ', end='') # Linea.objects.filter(envolvente__intersects=aa.geometry_simple).update(country_code=cc) print(Linea.objects \ .annotate(intersection_area=Area(Intersection(F('envolvente'), aa.geometry_simple)) / Area(F('envolvente'))) \ .filter(intersection_area__gt=A(sq_m=0.65)) \ .update(country_code=cc)) print(' - Recorrido: ', end='') print(Recorrido.objects \ .annotate(intersection_len=Length(Intersection(F('ruta_simple'), aa.geometry_simple)) / Length(F('ruta_simple'))) \ .filter(intersection_len__gt=D(m=0.65)) \ .update(country_code=cc)) print(' - Parada: ', end='') print( Parada.objects.filter( latlng__intersects=aa.geometry_simple).update( country_code=cc)) print(' - Poi: ', end='') print( Poi.objects.filter( latlng__intersects=aa.geometry_simple).update( country_code=cc)) print(' - AdministrativeArea: ', end='') print(AdministrativeArea.objects \ .annotate(intersection_area=Area(Intersection(F('geometry_simple'), aa.geometry_simple)) / Area(F('geometry_simple'))) \ .filter(intersection_area__gt=A(sq_m=0.65)) \ .update(country_code=cc)) print(' > DONE')
def update_flows(created): # compute distance ids = [c.id for c in created] routings = Routing.objects.filter(id__in=ids) routings.update(distance=Length(F('geom'))) queryset = Flow.objects for c in created: # fetch all flows with origin / destination & update flows = queryset.filter(Q(origin__id=c.origin.id) &\ Q(destination__id=c.destination.id)) flows.update(routing=c.pk)
def _filter_on_geom_size(self, layer_query, layer_geometry, pixel_width_x, pixel_width_y): if self.layer.is_linestring: # Larger then a half of pixel layer_query = layer_query.annotate( length3857=Length('outgeom3857')).filter( length3857__gt=(pixel_width_x + pixel_width_y) / 2 / 2) elif self.layer.is_polygon: # Larger than a quarter of pixel layer_query = layer_query.annotate( area3857=Area('outgeom3857')).filter( area3857__gt=pixel_width_x * pixel_width_y / 4) return layer_query
def queryset(self, request, queryset): if self.value() == 'blank': queryset = queryset.filter(track__isnull=True) return queryset if self.value() in ('valid', 'invalid'): queryset = queryset.annotate(length=Length('track')) if self.value() == 'valid': queryset = queryset.filter(length__gt=0) else: queryset = queryset.filter(length__lte=0) return queryset return queryset
def calculate_router_len_km(cls, route_id: str) -> Optional[float]: """ Calculates the router using the length gis internal function and convert it in km. :raise RouteLenCantNotBeCalculated """ route = Route.objects.annotate(length=Length('coordinates'))\ .filter(id=route_id) if not route: raise RouteLenCantNotBeCalculated() return route.last().length.m / 1000
def export_street_segments(request, street_id): response = HttpResponse(content_type='application/ms-excel') street = Street.objects.get(id=street_id) filename = '{}:{}.xls'.format(street.type.name, street.name) response[ 'Content-Disposition'] = "attachment; filename*=UTF-8''" + escape_uri_path( filename) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Segments') # Sheet header, first row row_num = 0 ws.write(row_num, 0, street.type.name + ": " + street.name) row_num = 1 font_style = xlwt.XFStyle() font_style.font.bold = True columns = [ 'id', 'Район', 'Довжина', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Segment.objects.filter(street__id=street_id).annotate( leng=(Length('geom'))) for row in rows: row_num += 1 ws.write(row_num, 0, row.id, font_style) ws.write(row_num, 1, row.district.name, font_style) ws.write(row_num, 2, str(row.leng), font_style) wb.save(response) return response
def get_length(self): annotated_qs = Segment.objects.filter(id=self.id).annotate( length=Length("geom", spheroid=True)) return annotated_qs.first().length
def length(self): length = GpxFile.objects.annotate(length=Length("track")).get( pk=self.pk).length if length: return round(length.km, 2)