Source code

Download source archive ↓

src/polygon_region.py

1"""Bounded WGS84 Polygon selection shared by HTTP validation and operators."""
2import math
3from shapely.geometry import Polygon,box
4
5MAX_VERTICES=256
6
7
8def selection(value):
9    if not isinstance(value,dict) or set(value)!={'type','coordinates'} or value.get('type')!='Polygon':
10        raise ValueError('region must be a GeoJSON Polygon geometry')
11    rings=value['coordinates']
12    if not isinstance(rings,list) or not rings or len(rings)>16:
13        raise ValueError('region requires an exterior ring and at most 15 holes')
14    if sum(len(r) for r in rings if isinstance(r,list))>MAX_VERTICES:
15        raise ValueError('region exceeds 256 vertices')
16    for ring in rings:
17        if not isinstance(ring,list) or len(ring)<4 or ring[0]!=ring[-1]:raise ValueError('polygon rings must be closed and have at least three vertices')
18        for coordinate in ring:
19            if not isinstance(coordinate,list) or len(coordinate)!=2 or any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in coordinate):raise ValueError('polygon coordinates must be finite longitude/latitude pairs')
20            lon,lat=coordinate
21            if not -180<=lon<=180 or not -85<lat<85:raise ValueError('polygon coordinates outside supported WGS84 range')
22    polygon=Polygon(rings[0],rings[1:])
23    if not polygon.is_valid or polygon.is_empty or polygon.area<=0:raise ValueError('polygon must be valid, nonempty and without self-intersections')
24    if polygon.bounds[2]-polygon.bounds[0]>180:raise ValueError('antimeridian-crossing regions are not supported')
25    return polygon
26
27
28def rectangle(bounds):
29    w,s,e,n=bounds
30    return {'type':'Polygon','coordinates':[[[w,s],[e,s],[e,n],[w,n],[w,s]]]}