-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathgeo.pyx
278 lines (200 loc) · 7.23 KB
/
geo.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
cimport h3lib
from h3lib cimport bool, H3int
from .util cimport (
check_cell,
check_edge,
check_res,
create_ptr,
create_mv,
deg2coord,
coord2deg,
)
from libc cimport stdlib
from .util import H3ValueError
cpdef H3int geo_to_h3(double lat, double lng, int res) except 1:
cdef:
h3lib.GeoCoord c
check_res(res)
c = deg2coord(lat, lng)
return h3lib.geoToH3(&c, res)
cpdef (double, double) h3_to_geo(H3int h) except *:
"""Map an H3 cell into its centroid geo-coordinate (lat/lng)"""
cdef:
h3lib.GeoCoord c
check_cell(h)
h3lib.h3ToGeo(h, &c)
return coord2deg(c)
cdef h3lib.Geofence make_geofence(geos, bool lnglat_order=False) except *:
"""
The returned `Geofence` must be freed with a call to `free_geofence`.
Parameters
----------
geos : list or tuple
GeoFence: A sequence of >= 3 (lat, lng) pairs where the last
element may or may not be same as the first (to form a closed loop).
The order of the pairs may be either clockwise or counterclockwise.
lnglat_order : bool
If True, assume coordinate pairs like (lng, lat)
If False, assume coordinate pairs like (lat, lng)
"""
cdef:
h3lib.Geofence gf
gf.numVerts = len(geos)
gf.verts = <h3lib.GeoCoord*> stdlib.calloc(gf.numVerts, sizeof(h3lib.GeoCoord))
if lnglat_order:
latlng = (g[::-1] for g in geos)
else:
latlng = geos
for i, (lat, lng) in enumerate(latlng):
gf.verts[i] = deg2coord(lat, lng)
return gf
cdef free_geofence(h3lib.Geofence* gf):
stdlib.free(gf.verts)
gf.verts = NULL
cdef class GeoPolygon:
cdef:
h3lib.GeoPolygon gp
def __cinit__(self, outer, holes=None, bool lnglat_order=False):
"""
Parameters
----------
outer : list or tuple
GeoFence
A GeoFence is a sequence of >= 3 (lat, lng) pairs where the last
element may or may not be same as the first (to form a closed loop).
The order of the pairs may be either clockwise or counterclockwise.
holes : list or tuple
A sequence of GeoFences
lnglat_order : bool
If True, assume coordinate pairs like (lng, lat)
If False, assume coordinate pairs like (lat, lng)
"""
if holes is None:
holes = []
self.gp.geofence = make_geofence(outer, lnglat_order)
self.gp.numHoles = len(holes)
self.gp.holes = NULL
if len(holes) > 0:
self.gp.holes = <h3lib.Geofence*> stdlib.calloc(len(holes), sizeof(h3lib.Geofence))
for i, hole in enumerate(holes):
self.gp.holes[i] = make_geofence(hole, lnglat_order)
def __dealloc__(self):
free_geofence(&self.gp.geofence)
for i in range(self.gp.numHoles):
free_geofence(&self.gp.holes[i])
stdlib.free(self.gp.holes)
def polyfill_polygon(outer, int res, holes=None, bool lnglat_order=False):
""" Set of hexagons whose center is contained in a polygon.
The polygon is defined as in the GeoJson standard, with an exterior
LinearRing `outer` and a list of LinearRings `holes`, which define any
holes in the polygon.
Each LinearRing may be in clockwise or counter-clockwise order
(right-hand rule or not), and may or may not be a closed loop (where the last
element is equal to the first).
The GeoJSON spec requires the right-hand rule, and a closed loop, but
this function will work with any input format.
Parameters
----------
outer : list or tuple
A LinearRing, a sequence of (lat/lng) or (lng/lat) pairs
res : int
The resolution of the output hexagons
holes : list or tuple
A collection of LinearRings, describing any holes in the polygon
lnglat_order : bool
If True, assume coordinate pairs like (lng, lat)
If False, assume coordinate pairs like (lat, lng)
"""
check_res(res)
gp = GeoPolygon(outer, holes=holes, lnglat_order=lnglat_order)
n = h3lib.maxPolyfillSize(&gp.gp, res)
ptr = create_ptr(n)
h3lib.polyfill(&gp.gp, res, ptr)
mv = create_mv(ptr, n)
return mv
def polyfill_geojson(geojson, int res):
""" Set of hexagons whose center is contained in a GeoJson Polygon object.
The polygon is defined exactly as in the GeoJson standard, so
`geojson` should be a dictionary like:
{
'type': 'Polygon',
'coordinates': [...]
}
'coordinates' should be a list of LinearRings, where the first ring describes
the exterior boundary of the Polygon, and any subsequent LinearRings
describe holes in the polygon.
Note that we don't provide an option for the order of the coordinates,
as the GeoJson standard requires them to be in lng/lat order.
Parameters
----------
geojson : dict
res : int
The resolution of the output hexagons
"""
# todo: this one could handle multipolygons...
if geojson['type'] != 'Polygon':
raise ValueError('Only Polygon GeoJSON supported')
coords = geojson['coordinates']
out = polyfill_polygon(coords[0], res, holes=coords[1:], lnglat_order=True)
return out
def polyfill(dict geojson, int res, bool geo_json_conformant=False):
""" Light wrapper around `polyfill_geojson` to provide backward compatibility.
"""
try:
gj_type = geojson['type']
except KeyError:
raise KeyError("`geojson` dict must have key 'type'.") from None
if gj_type != 'Polygon':
raise ValueError('Only Polygon GeoJSON supported')
if geo_json_conformant:
out = polyfill_geojson(geojson, res)
else:
coords = geojson['coordinates']
out = polyfill_polygon(coords[0], res, holes=coords[1:], lnglat_order=False)
return out
def cell_boundary(H3int h, bool geo_json=False):
"""Compose an array of geo-coordinates that outlines a hexagonal cell"""
cdef:
h3lib.GeoBoundary gb
check_cell(h)
h3lib.h3ToGeoBoundary(h, &gb)
verts = tuple(
coord2deg(gb.verts[i])
for i in range(gb.num_verts)
)
if geo_json:
#lat/lng -> lng/lat and last point same as first
verts += (verts[0],)
verts = tuple(v[::-1] for v in verts)
return verts
def edge_boundary(H3int edge, bool geo_json=False):
""" Returns the GeoBoundary containing the coordinates of the edge
"""
cdef:
h3lib.GeoBoundary gb
check_edge(edge)
h3lib.getH3UnidirectionalEdgeBoundary(edge, &gb)
# todo: move this verts transform into the GeoBoundary object
verts = tuple(
coord2deg(gb.verts[i])
for i in range(gb.num_verts)
)
if geo_json:
#lat/lng -> lng/lat and last point same as first
verts += (verts[0],)
verts = tuple(v[::-1] for v in verts)
return verts
cpdef double point_dist(
double lat1, double lng1,
double lat2, double lng2, unit='km') except -1:
a = deg2coord(lat1, lng1)
b = deg2coord(lat2, lng2)
if unit == 'rads':
d = h3lib.pointDistRads(&a, &b)
elif unit == 'km':
d = h3lib.pointDistKm(&a, &b)
elif unit == 'm':
d = h3lib.pointDistM(&a, &b)
else:
raise H3ValueError('Unknown unit: {}'.format(unit))
return d