-
Notifications
You must be signed in to change notification settings - Fork 395
Expand file tree
/
Copy path_geoslib.pyx
More file actions
498 lines (437 loc) · 16.3 KB
/
Copy path_geoslib.pyx
File metadata and controls
498 lines (437 loc) · 16.3 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import sys
import numpy
cimport numpy as cnp
__version__ = "2.1.0.dev0"
# Need some Python C-API functions for strings.
cdef extern from "Python.h":
object PyBytes_FromString(char *)
# Taken from `numpy.pxi` in numpy 1.0rc2.
cdef extern from "numpy/arrayobject.h":
ctypedef int npy_intp
ctypedef extern class numpy.ndarray [object PyArrayObject]:
cdef char *data
cdef int nd
cdef npy_intp *dimensions
cdef npy_intp *strides
cdef object base
cdef int flags
npy_intp PyArray_SIZE(ndarray arr)
npy_intp PyArray_ISCONTIGUOUS(ndarray arr)
# Initialize numpy.
cnp.import_array()
# GENERAL NOTES:
# - Remember to call initGEOS() before any use of this library's
# functions, and call finishGEOS() when done.
# - Currently you have to explicitly GEOSGeom_destroy() all
# GEOSGeom objects to avoid memory leaks, and to free()
# all returned char * (unless const). This might change
# before first release to ensure greater API stability.
cdef extern from "geos_c.h":
# Supported geometry type IDs.
cdef enum:
GEOS_POINT
GEOS_LINESTRING
GEOS_LINEARRING
GEOS_POLYGON
GEOS_MULTIPOINT
GEOS_MULTILINESTRING
GEOS_MULTIPOLYGON
GEOS_GEOMETRYCOLLECTION
GEOS_VERSION_MAJOR
ctypedef struct GEOSGeometry:
pass
ctypedef struct GEOSCoordSequence:
pass
# Cython 3: Next ctypedef needs "noexcept" declaration unless
# the compiler directive "legacy_implicit_noexcept" is used
# ("noexcept" syntax supported since Cython 0.29.31).
ctypedef void (*GEOSMessageHandler)(const char *fmt, ...)
char *GEOSversion()
void initGEOS(GEOSMessageHandler notice_function, GEOSMessageHandler error_function)
void finishGEOS()
GEOSCoordSequence *GEOSCoordSeq_create(unsigned int size, unsigned int dims)
void GEOSCoordSeq_destroy(GEOSCoordSequence* s)
int GEOSCoordSeq_setX(GEOSCoordSequence* s, unsigned int idx, double val)
int GEOSCoordSeq_setY(GEOSCoordSequence* s, unsigned int idx, double val)
int GEOSCoordSeq_getX(GEOSCoordSequence* s, unsigned int idx, double *val)
int GEOSCoordSeq_getY(GEOSCoordSequence* s, unsigned int idx, double *val)
GEOSGeometry *GEOSUnion(GEOSGeometry* g1, GEOSGeometry* g2)
GEOSGeometry *GEOSUnaryUnion(GEOSGeometry* g1)
GEOSGeometry *GEOSEnvelope(GEOSGeometry* g1)
GEOSGeometry *GEOSConvexHull(GEOSGeometry* g1)
GEOSGeometry *GEOSGeom_createPoint(GEOSCoordSequence* s)
GEOSGeometry *GEOSGeom_createLineString(GEOSCoordSequence* s)
GEOSGeometry *GEOSGeom_createPolygon(GEOSGeometry* shell, GEOSGeometry** holes, unsigned int nholes)
GEOSGeometry *GEOSGeom_createLinearRing(GEOSCoordSequence* s)
void GEOSGeom_destroy(GEOSGeometry* g)
# Topology operations: Return NULL on exception.
GEOSGeometry *GEOSIntersection(GEOSGeometry* g1, GEOSGeometry* g2)
GEOSGeometry *GEOSSimplify(GEOSGeometry* g1, double tolerance)
GEOSGeometry *GEOSBuffer(GEOSGeometry* g1, double width, int quadsegs)
GEOSGeometry *GEOSTopologyPreserveSimplify(GEOSGeometry* g1, double tolerance)
# Binary/Unary predicate: Return 2 on exception, 1 on true, 0 on false.
char GEOSIntersects(GEOSGeometry* g1, GEOSGeometry* g2)
char GEOSWithin(GEOSGeometry* g1, GEOSGeometry* g2)
char GEOSContains(GEOSGeometry* g1, GEOSGeometry* g2)
char GEOSisEmpty(GEOSGeometry* g1)
char GEOSisValid(GEOSGeometry* g1)
char GEOSisSimple(GEOSGeometry* g1)
char GEOSisRing(GEOSGeometry* g1)
# Geometry info.
char *GEOSGeomType(GEOSGeometry* g1)
int GEOSGeomTypeId(GEOSGeometry* g1)
# Functions: Return 0 on exception, 1 otherwise.
int GEOSArea(GEOSGeometry* g1, double *area)
int GEOSLength(GEOSGeometry* g1, double *length)
# Returns -1 on error and 1 for non-multi geoms.
int GEOSGetNumGeometries(GEOSGeometry* g1)
# Return NULL on exception, Geometry must be a Collection.
# Returned object is a pointer to internal storage:
# it must NOT be destroyed directly.
GEOSGeometry *GEOSGetGeometryN(GEOSGeometry* g, int n)
int GEOSGetNumInteriorRings(GEOSGeometry* g1)
# Return NULL on exception, Geometry must be a Polygon.
# Returned object is a pointer to internal storage:
# it must NOT be destroyed directly.
GEOSGeometry *GEOSGetExteriorRing(GEOSGeometry* g)
# Return NULL on exception.
# Geometry must be a LineString, LinearRing or Point.
GEOSCoordSequence *GEOSGeom_getCoordSeq(const GEOSGeometry* g)
int GEOSCoordSeq_getSize(const GEOSCoordSequence *s, unsigned int *size)
# Cython 3: Next cdef needs "noexcept" declaration unless
# the compiler directive "legacy_implicit_noexcept" is used
# ("noexcept" syntax supported since Cython 0.29.31).
cdef void notice_h(const char *fmt, ...) noexcept:
pass
#format = PyBytes_FromString(fmt)
#message = PyBytes_FromString(msg)
#try:
# warn_msg = format % message
#except:
# warn_msg = format
#sys.stdout.write('GEOS_NOTICE: %s\n' % warn_msg)
# Cython 3: Next cdef needs "noexcept" declaration unless
# the compiler directive "legacy_implicit_noexcept" is used
# ("noexcept" syntax supported since Cython 0.29.31).
# FIXME: The type should be: error_h(const char *fmt, ...), but
# Cython does not currently support varargs functions.
cdef void error_h(const char *fmt, char*msg):
format = PyBytes_FromString(fmt)
message = PyBytes_FromString(msg)
try:
warn_msg = format % message
except:
warn_msg = format
sys.stderr.write('GEOS_ERROR: %s\n' % warn_msg)
# Check library version.
cdef geos_version():
return PyBytes_FromString(GEOSversion())
# Module variables.
__geos_version__ = geos_version()
__geos_major_version__ = GEOS_VERSION_MAJOR
# Initialize GEOS (parameters are notice and error function callbacks).
initGEOS(notice_h, <GEOSMessageHandler>error_h)
cdef class BaseGeometry:
cdef GEOSGeometry *_geom
cdef unsigned int _npts
cdef public object boundary
def is_valid(self):
cdef char valid
valid = GEOSisValid(self._geom)
if valid:
return True
else:
return False
def geom_type(self):
return PyBytes_FromString(GEOSGeomType(self._geom))
def within(self, BaseGeometry geom):
cdef GEOSGeometry *g1
cdef GEOSGeometry *g2
cdef char answer
g1 = self._geom
g2 = geom._geom
answer = GEOSWithin(g1, g2)
if answer:
return True
else:
return False
def union(self, BaseGeometry geom):
cdef GEOSGeometry *g1
cdef GEOSGeometry *g2
cdef GEOSGeometry *g3
cdef const GEOSGeometry *gout
cdef int numgeoms, i, typeid
g1 = self._geom
g2 = geom._geom
g3 = GEOSUnion(g1, g2)
typeid = GEOSGeomTypeId(g3)
if typeid == GEOS_POLYGON:
b = _get_coords(g3)
p = Polygon(b)
elif typeid == GEOS_LINESTRING:
b = _get_coords(g3)
p = LineString(b)
# For multi-geom structures, just return first one.
elif typeid == GEOS_MULTIPOLYGON:
numgeoms = GEOSGetNumGeometries(g3)
gout = GEOSGetGeometryN(g3, 0)
b = _get_coords(gout)
p = Polygon(b)
elif typeid == GEOS_MULTILINESTRING:
numgeoms = GEOSGetNumGeometries(g3)
gout = GEOSGetGeometryN(g3, 0)
b = _get_coords(gout)
p = LineString(b)
else:
type = PyBytes_FromString(GEOSGeomType(g3))
raise NotImplementedError("unions of type '%s' not yet implemented" % (type))
GEOSGeom_destroy(g3)
return p
def simplify(self, tol):
cdef GEOSGeometry *g1
cdef GEOSGeometry *g3
cdef const GEOSGeometry *gout
cdef double tolerance
cdef int numgeoms, i, typeid
g1 = self._geom
tolerance = tol
g3 = GEOSSimplify(g1, tolerance)
typeid = GEOSGeomTypeId(g3)
if typeid == GEOS_POLYGON:
b = _get_coords(g3)
p = Polygon(b)
elif typeid == GEOS_LINESTRING:
b = _get_coords(g3)
p = LineString(b)
# For multi-geom structures, just return first one.
elif typeid == GEOS_MULTIPOLYGON:
numgeoms = GEOSGetNumGeometries(g3)
gout = GEOSGetGeometryN(g3, 0)
b = _get_coords(gout)
p = Polygon(b)
elif typeid == GEOS_MULTILINESTRING:
numgeoms = GEOSGetNumGeometries(g3)
gout = GEOSGetGeometryN(g3, 0)
b = _get_coords(gout)
p = LineString(b)
else:
type = PyBytes_FromString(GEOSGeomType(g3))
raise NotImplementedError("intersections of type '%s' not yet implemented" % (type))
GEOSGeom_destroy(g3)
return p
def fix(self):
cdef GEOSGeometry *g1
cdef GEOSGeometry *g3
cdef const GEOSGeometry *gout
cdef int numgeoms, i, typeid
g1 = self._geom
g3 = GEOSBuffer(g1, 0., 0)
typeid = GEOSGeomTypeId(g3)
if typeid == GEOS_POLYGON:
b = _get_coords(g3)
p = Polygon(b)
elif typeid == GEOS_LINESTRING:
b = _get_coords(g3)
p = LineString(b)
# For multi-geom structures, just return first one.
elif typeid == GEOS_MULTIPOLYGON:
numgeoms = GEOSGetNumGeometries(g3)
gout = GEOSGetGeometryN(g3, 0)
b = _get_coords(gout)
p = Polygon(b)
elif typeid == GEOS_MULTILINESTRING:
numgeoms = GEOSGetNumGeometries(g3)
gout = GEOSGetGeometryN(g3, 0)
b = _get_coords(gout)
p = LineString(b)
else:
type = PyBytes_FromString(GEOSGeomType(g3))
raise NotImplementedError("intersections of type '%s' not yet implemented" % (type))
GEOSGeom_destroy(g3)
return p
def intersects(self, BaseGeometry geom):
cdef GEOSGeometry *g1
cdef GEOSGeometry *g2
cdef char answer
g1 = self._geom
g2 = geom._geom
answer = GEOSIntersects(g1, g2)
if answer:
return True
else:
return False
def intersection(self, BaseGeometry geom):
cdef GEOSGeometry *g1
cdef GEOSGeometry *g2
cdef GEOSGeometry *g3
cdef const GEOSGeometry *gout
cdef char answer
cdef int numgeoms, i, typeid
g1 = self._geom
g2 = geom._geom
g3 = GEOSIntersection(g1, g2)
typeid = GEOSGeomTypeId(g3)
if typeid == GEOS_POLYGON:
b = _get_coords(g3)
p = Polygon(b)
pout = [p]
elif typeid == GEOS_LINESTRING:
b = _get_coords(g3)
p = LineString(b)
pout = [p]
elif typeid == GEOS_MULTIPOLYGON:
numgeoms = GEOSGetNumGeometries(g3)
pout = []
for i in range(numgeoms):
gout = GEOSGetGeometryN(g3, i)
b = _get_coords(gout)
p = Polygon(b)
pout.append(p)
elif typeid == GEOS_MULTILINESTRING:
numgeoms = GEOSGetNumGeometries(g3)
pout = []
for i in range(numgeoms):
gout = GEOSGetGeometryN(g3, i)
b = _get_coords(gout)
p = LineString(b)
pout.append(p)
elif typeid == GEOS_GEOMETRYCOLLECTION:
numgeoms = GEOSGetNumGeometries(g3)
pout = []
for i in range(numgeoms):
gout = GEOSGetGeometryN(g3, i)
typeid = GEOSGeomTypeId(gout)
if typeid == GEOS_POLYGON:
b = _get_coords(gout)
p = Polygon(b)
pout.append(p)
elif typeid == GEOS_LINESTRING:
b = _get_coords(gout)
p = LineString(b)
pout.append(p)
else:
# More cases might need to be handled here:
# - GEOS_MULTILINESTRING
# - GEOS_MULTIPOLYGON
# - GEOS_GEOMETRYCOLLECTION
# The underlying problem is the need of a generic
# converter from GEOSGeom pointers to `_geoslib`
# objects, since postprocessing `GeometryCollections`
# might need recursiveness.
pass
else:
#type = PyBytes_FromString(GEOSGeomType(g3))
#raise NotImplementedError("intersections of type '%s' not yet implemented" % (type))
GEOSGeom_destroy(g3)
return []
GEOSGeom_destroy(g3)
return pout
def get_coords(self):
return _get_coords(self._geom)
def __dealloc__(self):
"""destroy GEOS geometry"""
GEOSGeom_destroy(self._geom)
def __reduce__(self):
"""special method that allows geos instance to be pickled"""
return (self.__class__, (self.boundary,))
cdef class Polygon(BaseGeometry):
def __init__(self, ndarray b):
cdef unsigned int M, m, i
cdef double dx, dy
cdef double *bbuffer
cdef GEOSCoordSequence *cs
cdef GEOSGeometry *lr
# Make sure data is contiguous. If not, make a local copy.
if not PyArray_ISCONTIGUOUS(b):
b = b.copy()
m = b.shape[0]
# Add closing coordinates to sequence?
if m > 0 and (b[-1, 0] != b[0, 0] or b[-1, 1] != b[0, 1]):
M = m + 1
else:
M = m
self._npts = M
# Create a coordinate sequence.
cs = GEOSCoordSeq_create(M, 2)
# Add to coordinate sequence.
bbuffer = <double *>b.data
for i in range(m):
dx = bbuffer[2 * i]
dy = bbuffer[2 * i + 1]
# Because of a bug in the GEOS C API, always set X before Y.
GEOSCoordSeq_setX(cs, i, dx)
GEOSCoordSeq_setY(cs, i, dy)
# Add closing coordinates to sequence?
if M > m:
dx = bbuffer[0]
dy = bbuffer[1]
GEOSCoordSeq_setX(cs, M - 1, dx)
GEOSCoordSeq_setY(cs, M - 1, dy)
# Create LinearRing.
lr = GEOSGeom_createLinearRing(cs)
# Create Polygon from LinearRing (assuming no holes).
self._geom = GEOSGeom_createPolygon(lr, NULL, 0)
self.boundary = b
def area(self):
cdef double area
GEOSArea(self._geom, &area)
return area
cdef class LineString(BaseGeometry):
def __init__(self, ndarray b):
cdef double dx, dy
cdef GEOSCoordSequence *cs
cdef int i, M
cdef double *bbuffer
# Make sure data is contiguous. If not, make a local copy.
if not PyArray_ISCONTIGUOUS(b):
b = b.copy()
M = b.shape[0]
self._npts = M
# Create a coordinate sequence.
cs = GEOSCoordSeq_create(M, 2)
# Add to coordinate sequence.
bbuffer = <double *>b.data
for i in range(M):
dx = bbuffer[2 * i]
dy = bbuffer[2 * i + 1]
# Because of a bug in the GEOS C API, always set X before Y.
GEOSCoordSeq_setX(cs, i, dx)
GEOSCoordSeq_setY(cs, i, dy)
# Create LineString.
self._geom = GEOSGeom_createLineString(cs)
self.boundary = b
cdef class Point(BaseGeometry):
cdef public x, y
def __init__(self, b):
cdef double dx, dy
cdef GEOSCoordSequence *cs
# Create a coordinate sequence.
cs = GEOSCoordSeq_create(1, 2)
dx = b[0]
dy = b[1]
GEOSCoordSeq_setX(cs, 0, dx)
GEOSCoordSeq_setY(cs, 0, dy)
self._geom = GEOSGeom_createPoint(cs)
self._npts = 1
self.boundary = b
cdef _get_coords(const GEOSGeometry *geom):
cdef const GEOSCoordSequence *cs
cdef const GEOSGeometry *lr
cdef unsigned int i, M
cdef double dx, dy
cdef ndarray b
cdef double *bbuffer
if GEOSGeomTypeId(geom) == GEOS_POLYGON:
lr = GEOSGetExteriorRing(geom)
cs = GEOSGeom_getCoordSeq(lr)
else:
cs = GEOSGeom_getCoordSeq(geom)
GEOSCoordSeq_getSize(cs, &M)
b = numpy.empty((M, 2), numpy.float64)
bbuffer = <double *>b.data
for i in range(M):
GEOSCoordSeq_getX(cs, i, &dx)
GEOSCoordSeq_getY(cs, i, &dy)
bbuffer[2 * i] = dx
bbuffer[2 * i + 1] = dy
return b