shapely 1.2.8__py2.6-win-amd64.egg

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. DLLs/geos.dll +0 -0
  2. DLLs/geos_c.dll +0 -0
  3. EGG-INFO/PKG-INFO +173 -0
  4. EGG-INFO/not-zip-safe +1 -0
  5. EGG-INFO/scripts/dissolve.py +53 -0
  6. EGG-INFO/scripts/intersect.py +81 -0
  7. shapely/__init__.py +1 -0
  8. shapely/__init__.pyc +0 -0
  9. shapely/coords.py +167 -0
  10. shapely/coords.pyc +0 -0
  11. shapely/ctypes_declarations.py +279 -0
  12. shapely/ctypes_declarations.pyc +0 -0
  13. shapely/ftools.py +78 -0
  14. shapely/ftools.pyc +0 -0
  15. shapely/geometry/__init__.py +20 -0
  16. shapely/geometry/__init__.pyc +0 -0
  17. shapely/geometry/base.py +595 -0
  18. shapely/geometry/base.pyc +0 -0
  19. shapely/geometry/collection.py +43 -0
  20. shapely/geometry/collection.pyc +0 -0
  21. shapely/geometry/geo.py +68 -0
  22. shapely/geometry/geo.pyc +0 -0
  23. shapely/geometry/linestring.py +259 -0
  24. shapely/geometry/linestring.pyc +0 -0
  25. shapely/geometry/multilinestring.py +133 -0
  26. shapely/geometry/multilinestring.pyc +0 -0
  27. shapely/geometry/multipoint.py +180 -0
  28. shapely/geometry/multipoint.pyc +0 -0
  29. shapely/geometry/multipolygon.py +154 -0
  30. shapely/geometry/multipolygon.pyc +0 -0
  31. shapely/geometry/point.py +241 -0
  32. shapely/geometry/point.pyc +0 -0
  33. shapely/geometry/polygon.py +449 -0
  34. shapely/geometry/polygon.pyc +0 -0
  35. shapely/geometry/proxy.py +54 -0
  36. shapely/geometry/proxy.pyc +0 -0
  37. shapely/geos.py +373 -0
  38. shapely/geos.pyc +0 -0
  39. shapely/impl.py +119 -0
  40. shapely/impl.pyc +0 -0
  41. shapely/iterops.py +53 -0
  42. shapely/iterops.pyc +0 -0
  43. shapely/linref.py +26 -0
  44. shapely/linref.pyc +0 -0
  45. shapely/ops.py +87 -0
  46. shapely/ops.pyc +0 -0
  47. shapely/predicates.py +24 -0
  48. shapely/predicates.pyc +0 -0
  49. shapely/prepared.py +58 -0
  50. shapely/prepared.pyc +0 -0
  51. shapely/topology.py +62 -0
  52. shapely/topology.pyc +0 -0
  53. shapely/validation.py +7 -0
  54. shapely/validation.pyc +0 -0
  55. shapely/wkb.py +39 -0
  56. shapely/wkb.pyc +0 -0
  57. shapely/wkt.py +34 -0
  58. shapely/wkt.pyc +0 -0
shapely/geos.py ADDED
@@ -0,0 +1,373 @@
1
+ """
2
+ Proxies for the libgeos_c shared lib, GEOS-specific exceptions, and utilities
3
+ """
4
+
5
+ import atexit
6
+ import logging
7
+ import os
8
+ import sys
9
+ import time
10
+ import threading
11
+ import ctypes
12
+ from ctypes import cdll, CDLL, PyDLL, CFUNCTYPE, c_char_p, c_void_p, string_at
13
+ from ctypes.util import find_library
14
+
15
+ import ftools
16
+ from ctypes_declarations import prototype
17
+
18
+
19
+
20
+ # Begin by creating a do-nothing handler and adding to this module's logger.
21
+ class NullHandler(logging.Handler):
22
+ def emit(self, record):
23
+ pass
24
+ LOG = logging.getLogger(__name__)
25
+ LOG.addHandler(NullHandler())
26
+
27
+ # Find and load the GEOS and C libraries
28
+ # If this ever gets any longer, we'll break it into separate modules
29
+
30
+ def load_dll(libname, fallbacks=None):
31
+ lib = find_library(libname)
32
+ if lib is not None:
33
+ return CDLL(lib)
34
+ else:
35
+ if fallbacks is not None:
36
+ for name in fallbacks:
37
+ try:
38
+ return CDLL(name)
39
+ except OSError:
40
+ # move on to the next fallback
41
+ pass
42
+ # the end
43
+ raise OSError(
44
+ "Could not find library %s or load any of its variants %s" % (
45
+ libname, fallbacks or []))
46
+
47
+ if sys.platform == 'linux2':
48
+ _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
49
+ free = load_dll('c').free
50
+ free.argtypes = [c_void_p]
51
+ free.restype = None
52
+
53
+ elif sys.platform == 'darwin':
54
+ alt_paths = [
55
+ # The Framework build from Kyng Chaos:
56
+ "/Library/Frameworks/GEOS.framework/Versions/Current/GEOS",
57
+ # macports
58
+ '/opt/local/lib/libgeos_c.dylib',
59
+ ]
60
+ _lgeos = load_dll('geos_c', fallbacks=alt_paths)
61
+ free = load_dll('c').free
62
+ free.argtypes = [c_void_p]
63
+ free.restype = None
64
+
65
+ elif sys.platform == 'win32':
66
+ try:
67
+ egg_dlls = os.path.abspath(os.path.join(os.path.dirname(__file__),
68
+ r"..\DLLs"))
69
+ wininst_dlls = os.path.abspath(os.__file__ + "../../../DLLs")
70
+ original_path = os.environ['PATH']
71
+ os.environ['PATH'] = "%s;%s;%s" % (egg_dlls, wininst_dlls, original_path)
72
+ _lgeos = CDLL("geos.dll")
73
+ except (ImportError, WindowsError, OSError):
74
+ raise
75
+ def free(m):
76
+ try:
77
+ cdll.msvcrt.free(m)
78
+ except WindowsError:
79
+ # XXX: See http://trac.gispython.org/projects/PCL/ticket/149
80
+ pass
81
+
82
+ elif sys.platform == 'sunos5':
83
+ _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
84
+ free = CDLL('libc.so.1').free
85
+ free.argtypes = [c_void_p]
86
+ free.restype = None
87
+
88
+ else: # other *nix systems
89
+ _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
90
+ free = load_dll('c', fallbacks=['libc.so.6']).free
91
+ free.argtypes = [c_void_p]
92
+ free.restype = None
93
+
94
+ def _geos_c_version():
95
+ func = _lgeos.GEOSversion
96
+ func.restype = c_char_p
97
+ v = func().split('-')[2]
98
+ return tuple(int(n) for n in v.split('.'))
99
+
100
+ geos_capi_version = geos_c_version = _geos_c_version()
101
+
102
+ # If we have the new interface, then record a baseline so that we know what
103
+ # additional functions are declared in ctypes_declarations.
104
+ if geos_c_version >= (1,5,0):
105
+ start_set = set(_lgeos.__dict__)
106
+
107
+ # Apply prototypes for the libgeos_c functions
108
+ prototype(_lgeos, geos_c_version)
109
+
110
+ # If we have the new interface, automatically detect all function
111
+ # declarations, and declare their re-entrant counterpart.
112
+ if geos_c_version >= (1,5,0):
113
+ end_set = set(_lgeos.__dict__)
114
+ new_func_names = end_set - start_set
115
+
116
+ for func_name in new_func_names:
117
+ new_func_name = "%s_r" % func_name
118
+ if hasattr(_lgeos, new_func_name):
119
+ new_func = getattr(_lgeos, new_func_name)
120
+ old_func = getattr(_lgeos, func_name)
121
+ new_func.restype = old_func.restype
122
+ if old_func.argtypes is None:
123
+ # Handle functions that didn't take an argument before,
124
+ # finishGEOS.
125
+ new_func.argtypes = [c_void_p]
126
+ else:
127
+ new_func.argtypes = [c_void_p] + old_func.argtypes
128
+ if old_func.errcheck is not None:
129
+ new_func.errcheck = old_func.errcheck
130
+
131
+ # Handle special case.
132
+ _lgeos.initGEOS_r.restype = c_void_p
133
+ _lgeos.initGEOS_r.argtypes = [c_void_p, c_void_p]
134
+ _lgeos.finishGEOS_r.argtypes = [c_void_p]
135
+
136
+ # Exceptions
137
+
138
+ class ReadingError(Exception):
139
+ pass
140
+
141
+ class DimensionError(Exception):
142
+ pass
143
+
144
+ class TopologicalError(Exception):
145
+ pass
146
+
147
+ class PredicateError(Exception):
148
+ pass
149
+
150
+ def error_handler(fmt, list):
151
+ LOG.error("%s", list)
152
+ error_h = CFUNCTYPE(None, c_char_p, c_char_p)(error_handler)
153
+
154
+ def notice_handler(fmt, list):
155
+ LOG.warning("%s", list)
156
+ notice_h = CFUNCTYPE(None, c_char_p, c_char_p)(notice_handler)
157
+
158
+ def cleanup():
159
+ if _lgeos is not None :
160
+ _lgeos.finishGEOS()
161
+
162
+ atexit.register(cleanup)
163
+
164
+ # Errcheck functions
165
+
166
+ def errcheck_wkb(result, func, argtuple):
167
+ if not result:
168
+ return None
169
+ size_ref = argtuple[-1]
170
+ size = size_ref._obj
171
+ retval = ctypes.string_at(result, size.value)[:]
172
+ lgeos.GEOSFree(result)
173
+ return retval
174
+
175
+ def errcheck_just_free(result, func, argtuple):
176
+ retval = string_at(result)
177
+ lgeos.GEOSFree(result)
178
+ return retval
179
+
180
+ def errcheck_predicate(result, func, argtuple):
181
+ if result == 2:
182
+ raise PredicateError("Failed to evaluate %s" % repr(func))
183
+ return result
184
+
185
+
186
+ class LGEOSBase(threading.local):
187
+ """Proxy for the GEOS_C DLL/SO
188
+
189
+ This is a base class. Do not instantiate.
190
+ """
191
+ methods = {}
192
+ def __init__(self, dll):
193
+ self._lgeos = dll
194
+ self.geos_handle = None
195
+
196
+
197
+ class LGEOS14(LGEOSBase):
198
+ """Proxy for the GEOS_C DLL/SO API version 1.4
199
+ """
200
+ geos_capi_version = (1, 4, 0)
201
+ def __init__(self, dll):
202
+ super(LGEOS14, self).__init__(dll)
203
+ self.geos_handle = self._lgeos.initGEOS(notice_h, error_h)
204
+ keys = self._lgeos.__dict__.keys()
205
+ for key in keys:
206
+ setattr(self, key, getattr(self._lgeos, key))
207
+ self.GEOSFree = self._lgeos.free
208
+ self.GEOSGeomToWKB_buf.errcheck = errcheck_wkb
209
+ self.GEOSGeomToWKT.errcheck = errcheck_just_free
210
+ self.GEOSRelate.errcheck = errcheck_just_free
211
+ for pred in ( self.GEOSDisjoint,
212
+ self.GEOSTouches,
213
+ self.GEOSIntersects,
214
+ self.GEOSCrosses,
215
+ self.GEOSWithin,
216
+ self.GEOSContains,
217
+ self.GEOSOverlaps,
218
+ self.GEOSEquals,
219
+ self.GEOSEqualsExact,
220
+ self.GEOSisEmpty,
221
+ self.GEOSisValid,
222
+ self.GEOSisSimple,
223
+ self.GEOSisRing,
224
+ self.GEOSHasZ
225
+ ):
226
+ pred.errcheck = errcheck_predicate
227
+
228
+ self.methods['area'] = self.GEOSArea
229
+ self.methods['boundary'] = self.GEOSBoundary
230
+ self.methods['buffer'] = self.GEOSBuffer
231
+ self.methods['centroid'] = self.GEOSGetCentroid
232
+ self.methods['representative_point'] = self.GEOSPointOnSurface
233
+ self.methods['convex_hull'] = self.GEOSConvexHull
234
+ self.methods['distance'] = self.GEOSDistance
235
+ self.methods['envelope'] = self.GEOSEnvelope
236
+ self.methods['length'] = self.GEOSLength
237
+ self.methods['has_z'] = self.GEOSHasZ
238
+ self.methods['is_empty'] = self.GEOSisEmpty
239
+ self.methods['is_ring'] = self.GEOSisRing
240
+ self.methods['is_simple'] = self.GEOSisSimple
241
+ self.methods['is_valid'] = self.GEOSisValid
242
+ self.methods['disjoint'] = self.GEOSDisjoint
243
+ self.methods['touches'] = self.GEOSTouches
244
+ self.methods['intersects'] = self.GEOSIntersects
245
+ self.methods['crosses'] = self.GEOSCrosses
246
+ self.methods['within'] = self.GEOSWithin
247
+ self.methods['contains'] = self.GEOSContains
248
+ self.methods['overlaps'] = self.GEOSOverlaps
249
+ self.methods['equals'] = self.GEOSEquals
250
+ self.methods['equals_exact'] = self.GEOSEqualsExact
251
+ self.methods['relate'] = self.GEOSRelate
252
+ self.methods['difference'] = self.GEOSDifference
253
+ self.methods['symmetric_difference'] = self.GEOSSymDifference
254
+ self.methods['union'] = self.GEOSUnion
255
+ self.methods['intersection'] = self.GEOSIntersection
256
+ self.methods['simplify'] = self.GEOSSimplify
257
+ self.methods['topology_preserve_simplify'] = \
258
+ self.GEOSTopologyPreserveSimplify
259
+
260
+
261
+ class LGEOS15(LGEOSBase):
262
+ """Proxy for the reentrant GEOS_C DLL/SO API version 1.5
263
+ """
264
+ geos_capi_version = (1, 5, 0)
265
+ def __init__(self, dll):
266
+ super(LGEOS15, self).__init__(dll)
267
+ self.geos_handle = self._lgeos.initGEOS_r(notice_h, error_h)
268
+ keys = self._lgeos.__dict__.keys()
269
+ for key in filter(lambda x: not x.endswith('_r'), keys):
270
+ if key + '_r' in keys:
271
+ reentr_func = getattr(self._lgeos, key + '_r')
272
+ attr = ftools.partial(reentr_func, self.geos_handle)
273
+ attr.__name__ = reentr_func.__name__
274
+ setattr(self, key, attr)
275
+ else:
276
+ setattr(self, key, getattr(self._lgeos, key))
277
+ if not hasattr(self, 'GEOSFree'):
278
+ self.GEOSFree = self._lgeos.free
279
+ self.GEOSGeomToWKB_buf.func.errcheck = errcheck_wkb
280
+ self.GEOSGeomToWKT.func.errcheck = errcheck_just_free
281
+ self.GEOSRelate.func.errcheck = errcheck_just_free
282
+ for pred in ( self.GEOSDisjoint,
283
+ self.GEOSTouches,
284
+ self.GEOSIntersects,
285
+ self.GEOSCrosses,
286
+ self.GEOSWithin,
287
+ self.GEOSContains,
288
+ self.GEOSOverlaps,
289
+ self.GEOSEquals,
290
+ self.GEOSEqualsExact,
291
+ self.GEOSisEmpty,
292
+ self.GEOSisValid,
293
+ self.GEOSisSimple,
294
+ self.GEOSisRing,
295
+ self.GEOSHasZ
296
+ ):
297
+ pred.func.errcheck = errcheck_predicate
298
+
299
+ self.GEOSisValidReason.func.errcheck = errcheck_just_free
300
+
301
+ self.methods['area'] = self.GEOSArea
302
+ self.methods['boundary'] = self.GEOSBoundary
303
+ self.methods['buffer'] = self.GEOSBuffer
304
+ self.methods['centroid'] = self.GEOSGetCentroid
305
+ self.methods['representative_point'] = self.GEOSPointOnSurface
306
+ self.methods['convex_hull'] = self.GEOSConvexHull
307
+ self.methods['distance'] = self.GEOSDistance
308
+ self.methods['envelope'] = self.GEOSEnvelope
309
+ self.methods['length'] = self.GEOSLength
310
+ self.methods['has_z'] = self.GEOSHasZ
311
+ self.methods['is_empty'] = self.GEOSisEmpty
312
+ self.methods['is_ring'] = self.GEOSisRing
313
+ self.methods['is_simple'] = self.GEOSisSimple
314
+ self.methods['is_valid'] = self.GEOSisValid
315
+ self.methods['disjoint'] = self.GEOSDisjoint
316
+ self.methods['touches'] = self.GEOSTouches
317
+ self.methods['intersects'] = self.GEOSIntersects
318
+ self.methods['crosses'] = self.GEOSCrosses
319
+ self.methods['within'] = self.GEOSWithin
320
+ self.methods['contains'] = self.GEOSContains
321
+ self.methods['overlaps'] = self.GEOSOverlaps
322
+ self.methods['equals'] = self.GEOSEquals
323
+ self.methods['equals_exact'] = self.GEOSEqualsExact
324
+ self.methods['relate'] = self.GEOSRelate
325
+ self.methods['difference'] = self.GEOSDifference
326
+ self.methods['symmetric_difference'] = self.GEOSSymDifference
327
+ self.methods['union'] = self.GEOSUnion
328
+ self.methods['intersection'] = self.GEOSIntersection
329
+ self.methods['prepared_intersects'] = self.GEOSPreparedIntersects
330
+ self.methods['prepared_contains'] = self.GEOSPreparedContains
331
+ self.methods['prepared_contains_properly'] = \
332
+ self.GEOSPreparedContainsProperly
333
+ self.methods['prepared_covers'] = self.GEOSPreparedCovers
334
+ self.methods['simplify'] = self.GEOSSimplify
335
+ self.methods['topology_preserve_simplify'] = \
336
+ self.GEOSTopologyPreserveSimplify
337
+
338
+ class LGEOS16(LGEOS15):
339
+ """Proxy for the reentrant GEOS_C DLL/SO API version 1.6
340
+ """
341
+ geos_capi_version = (1, 6, 0)
342
+ def __init__(self, dll):
343
+ super(LGEOS16, self).__init__(dll)
344
+
345
+
346
+ class LGEOS16LR(LGEOS16):
347
+ """Proxy for the reentrant GEOS_C DLL/SO API version 1.6 with linear
348
+ referencing
349
+ """
350
+ geos_capi_version = geos_c_version
351
+ def __init__(self, dll):
352
+ super(LGEOS16LR, self).__init__(dll)
353
+
354
+ self.methods['parallel_offset'] = self.GEOSSingleSidedBuffer
355
+ self.methods['project'] = self.GEOSProject
356
+ self.methods['project_normalized'] = self.GEOSProjectNormalized
357
+ self.methods['interpolate'] = self.GEOSInterpolate
358
+ self.methods['interpolate_normalized'] = \
359
+ self.GEOSInterpolateNormalized
360
+
361
+
362
+ if geos_c_version >= (1, 6, 0):
363
+ if hasattr(_lgeos, 'GEOSProject'):
364
+ L = LGEOS16LR
365
+ else:
366
+ L = LGEOS16
367
+ elif geos_c_version >= (1, 5, 0):
368
+ L = LGEOS15
369
+ else:
370
+ L = LGEOS14
371
+
372
+ lgeos = L(_lgeos)
373
+
shapely/geos.pyc ADDED
Binary file
shapely/impl.py ADDED
@@ -0,0 +1,119 @@
1
+ """Implementation of the intermediary layer between Shapely and GEOS
2
+
3
+ This is layer number 2 from the list below.
4
+
5
+ 1) geometric objects: the Python OO API.
6
+ 2) implementation map: an abstraction that permits different backends.
7
+ 3) backend: callable objects that take Shapely geometric objects as arguments
8
+ and, with GEOS as a backend, translate them to C data structures.
9
+ 4) GEOS library: algorithms implemented in C++.
10
+
11
+ Shapely 1.2 includes a GEOS backend and it is the default.
12
+ """
13
+
14
+ from ftools import wraps
15
+
16
+ from shapely.coords import BoundsOp
17
+ from shapely.geos import lgeos
18
+ from shapely.linref import ProjectOp, InterpolateOp
19
+ from shapely.predicates import BinaryPredicate, UnaryPredicate
20
+ from shapely.topology import BinaryRealProperty, BinaryTopologicalOp
21
+ from shapely.topology import UnaryRealProperty, UnaryTopologicalOp
22
+
23
+ def delegated(func):
24
+ """A delegated method raises AttributeError in the absence of backend
25
+ support."""
26
+ @wraps(func)
27
+ def wrapper(*args, **kwargs):
28
+ try:
29
+ return func(*args, **kwargs)
30
+ except KeyError:
31
+ raise AttributeError, "Method '%s' is not supported by %s" % (
32
+ func.__name__, repr(args[0].impl))
33
+ return wrapper
34
+
35
+ # Map geometry methods to their GEOS delegates
36
+
37
+ class BaseImpl(object):
38
+ def __init__(self, values):
39
+ self.map = dict(values)
40
+ def update(self, values):
41
+ self.map.update(values)
42
+ def __getitem__(self, key):
43
+ return self.map[key]
44
+
45
+ class GEOSImpl(BaseImpl):
46
+ def __repr__(self):
47
+ return '<GEOSImpl object: GEOS C API version %s>' % (
48
+ lgeos.geos_capi_version,)
49
+
50
+ IMPL14 = {
51
+ 'area': (UnaryRealProperty, 'area'),
52
+ 'distance': (BinaryRealProperty, 'distance'),
53
+ 'length': (UnaryRealProperty, 'length'),
54
+ #
55
+ 'boundary': (UnaryTopologicalOp, 'boundary'),
56
+ 'bounds': (BoundsOp, None),
57
+ 'centroid': (UnaryTopologicalOp, 'centroid'),
58
+ 'representative_point': (UnaryTopologicalOp, 'representative_point'),
59
+ 'envelope': (UnaryTopologicalOp, 'envelope'),
60
+ 'convex_hull': (UnaryTopologicalOp, 'convex_hull'),
61
+ 'buffer': (UnaryTopologicalOp, 'buffer'),
62
+ #
63
+ 'difference': (BinaryTopologicalOp, 'difference'),
64
+ 'intersection': (BinaryTopologicalOp, 'intersection'),
65
+ 'symmetric_difference': (BinaryTopologicalOp, 'symmetric_difference'),
66
+ 'union': (BinaryTopologicalOp, 'union'),
67
+ #
68
+ 'has_z': (UnaryPredicate, 'has_z'),
69
+ 'is_empty': (UnaryPredicate, 'is_empty'),
70
+ 'is_ring': (UnaryPredicate, 'is_ring'),
71
+ 'is_simple': (UnaryPredicate, 'is_simple'),
72
+ 'is_valid': (UnaryPredicate, 'is_valid'),
73
+ #
74
+ 'relate': (BinaryPredicate, 'relate'),
75
+ 'contains': (BinaryPredicate, 'contains'),
76
+ 'crosses': (BinaryPredicate, 'crosses'),
77
+ 'disjoint': (BinaryPredicate, 'disjoint'),
78
+ 'equals': (BinaryPredicate, 'equals'),
79
+ 'intersects': (BinaryPredicate, 'intersects'),
80
+ 'overlaps': (BinaryPredicate, 'overlaps'),
81
+ 'touches': (BinaryPredicate, 'touches'),
82
+ 'within': (BinaryPredicate, 'within'),
83
+ 'equals_exact': (BinaryPredicate, 'equals_exact'),
84
+ }
85
+
86
+ IMPL15 = {
87
+ 'simplify': (UnaryTopologicalOp, 'simplify'),
88
+ 'topology_preserve_simplify':
89
+ (UnaryTopologicalOp, 'topology_preserve_simplify'),
90
+ 'prepared_intersects': (BinaryPredicate, 'prepared_intersects'),
91
+ 'prepared_contains': (BinaryPredicate, 'prepared_contains'),
92
+ 'prepared_contains_properly':
93
+ (BinaryPredicate, 'prepared_contains_properly'),
94
+ 'prepared_covers': (BinaryPredicate, 'prepared_covers'),
95
+ }
96
+
97
+ IMPL16 = {
98
+ }
99
+
100
+ IMPL16LR = {
101
+ 'parallel_offset': (UnaryTopologicalOp, 'parallel_offset'),
102
+ 'project_normalized': (ProjectOp, 'project_normalized'),
103
+ 'project': (ProjectOp, 'project'),
104
+ 'interpolate_normalized': (InterpolateOp, 'interpolate_normalized'),
105
+ 'interpolate': (InterpolateOp, 'interpolate'),
106
+ }
107
+
108
+ def impl_items(defs):
109
+ return [(k, v[0](v[1])) for k, v in defs.items()]
110
+
111
+ imp = GEOSImpl(dict(impl_items(IMPL14)))
112
+ if lgeos.geos_capi_version >= (1, 5, 0):
113
+ imp.update(impl_items(IMPL15))
114
+ if lgeos.geos_capi_version >= (1, 6, 0):
115
+ imp.update(impl_items(IMPL16))
116
+ if 'project' in lgeos.methods:
117
+ imp.update(impl_items(IMPL16LR))
118
+
119
+ DefaultImplementation = imp
shapely/impl.pyc ADDED
Binary file
shapely/iterops.py ADDED
@@ -0,0 +1,53 @@
1
+ """
2
+ Iterative forms of operations
3
+ """
4
+
5
+ from ctypes import c_char_p, c_size_t
6
+ from shapely.geos import lgeos, free
7
+
8
+
9
+ def geos_from_geometry(geom):
10
+ data = geom.to_wkb()
11
+ return lgeos.GEOSGeomFromWKB_buf(
12
+ c_char_p(data),
13
+ c_size_t(len(data))
14
+ )
15
+
16
+
17
+ class IterOp(object):
18
+
19
+ """A generating non-data descriptor.
20
+ """
21
+
22
+ def __init__(self, fn):
23
+ self.fn = fn
24
+
25
+ def __call__(self, context, iterator, value=True):
26
+ if context._geom is None:
27
+ raise ValueError("Null geometry supports no operations")
28
+ for item in iterator:
29
+ try:
30
+ this_geom, ob = item
31
+ except TypeError:
32
+ this_geom = item
33
+ ob = this_geom
34
+ if not this_geom._geom:
35
+ raise ValueError("Null geometry supports no operations")
36
+ retval = self.fn(context._geom, this_geom._geom)
37
+ if retval == 2:
38
+ raise PredicateError(
39
+ "Failed to evaluate %s" % repr(self.fn))
40
+ elif bool(retval) == value:
41
+ yield ob
42
+
43
+
44
+ # utilities
45
+ disjoint = IterOp(lgeos.GEOSDisjoint)
46
+ touches = IterOp(lgeos.GEOSTouches)
47
+ intersects = IterOp(lgeos.GEOSIntersects)
48
+ crosses = IterOp(lgeos.GEOSCrosses)
49
+ within = IterOp(lgeos.GEOSWithin)
50
+ contains = IterOp(lgeos.GEOSContains)
51
+ overlaps = IterOp(lgeos.GEOSOverlaps)
52
+ equals = IterOp(lgeos.GEOSEquals)
53
+
shapely/iterops.pyc ADDED
Binary file
shapely/linref.py ADDED
@@ -0,0 +1,26 @@
1
+ """Linear referencing
2
+ """
3
+
4
+ from shapely.topology import Delegating
5
+
6
+
7
+ class LinearRefBase(Delegating):
8
+ def _validate_line(self, ob):
9
+ super(LinearRefBase, self)._validate(ob)
10
+ try:
11
+ assert ob.geom_type in ['LineString', 'MultiLineString']
12
+ except AssertionError:
13
+ raise TypeError("Only linear types support this operation")
14
+
15
+ class ProjectOp(LinearRefBase):
16
+ def __call__(self, this, other):
17
+ self._validate_line(this)
18
+ self._validate(other)
19
+ return self.fn(this._geom, other._geom)
20
+
21
+ class InterpolateOp(LinearRefBase):
22
+ def __call__(self, this, distance):
23
+ self._validate_line(this)
24
+ return self.fn(this._geom, distance)
25
+
26
+
shapely/linref.pyc ADDED
Binary file
shapely/ops.py ADDED
@@ -0,0 +1,87 @@
1
+ """Support for various GEOS geometry operations
2
+ """
3
+
4
+ from ctypes import byref, c_void_p
5
+
6
+ from shapely.geos import lgeos
7
+ from shapely.geometry.base import geom_factory, BaseGeometry
8
+ from shapely.geometry import asShape, asLineString, asMultiLineString
9
+
10
+ __all__= ['operator', 'polygonize', 'linemerge', 'cascaded_union']
11
+
12
+
13
+ class CollectionOperator(object):
14
+
15
+ def shapeup(self, ob):
16
+ if isinstance(ob, BaseGeometry):
17
+ return ob
18
+ else:
19
+ try:
20
+ return asShape(ob)
21
+ except ValueError:
22
+ return asLineString(ob)
23
+
24
+ def polygonize(self, lines):
25
+ """Creates polygons from a source of lines
26
+
27
+ The source may be a MultiLineString, a sequence of LineString objects,
28
+ or a sequence of objects than can be adapted to LineStrings.
29
+ """
30
+ source = getattr(lines, 'geoms', None) or lines
31
+ obs = [self.shapeup(l) for l in source]
32
+ geom_array_type = c_void_p * len(obs)
33
+ geom_array = geom_array_type()
34
+ for i, line in enumerate(obs):
35
+ geom_array[i] = line._geom
36
+ product = lgeos.GEOSPolygonize(byref(geom_array), len(obs))
37
+ collection = geom_factory(product)
38
+ for g in collection.geoms:
39
+ clone = lgeos.GEOSGeom_clone(g._geom)
40
+ g = geom_factory(clone)
41
+ g._owned = False
42
+ yield g
43
+
44
+ def linemerge(self, lines):
45
+ """Merges all connected lines from a source
46
+
47
+ The source may be a MultiLineString, a sequence of LineString objects,
48
+ or a sequence of objects than can be adapted to LineStrings. Returns a
49
+ LineString or MultiLineString when lines are not contiguous.
50
+ """
51
+ source = None
52
+ if hasattr(lines, 'type') and lines.type == 'MultiLineString':
53
+ source = lines
54
+ elif hasattr(lines, '__iter__'):
55
+ try:
56
+ source = asMultiLineString([ls.coords for ls in lines])
57
+ except AttributeError:
58
+ source = asMultiLineString(lines)
59
+ if source is None:
60
+ raise ValueError("Cannot linemerge %s" % lines)
61
+ result = lgeos.GEOSLineMerge(source._geom)
62
+ return geom_factory(result)
63
+
64
+ def cascaded_union(self, geoms):
65
+ """Returns the union of a sequence of geometries
66
+
67
+ This is the most efficient method of dissolving many polygons.
68
+ """
69
+ L = len(geoms)
70
+ subs = (c_void_p * L)()
71
+ for i, g in enumerate(geoms):
72
+ subs[i] = g._geom
73
+ collection = lgeos.GEOSGeom_createCollection(6, subs, L)
74
+ return geom_factory(lgeos.GEOSUnionCascaded(collection))
75
+
76
+
77
+ operator = CollectionOperator()
78
+ polygonize = operator.polygonize
79
+ linemerge = operator.linemerge
80
+ cascaded_union = operator.cascaded_union
81
+
82
+ class ValidateOp(object):
83
+ def __call__(self, this):
84
+ return lgeos.GEOSisValidReason(this._geom)
85
+
86
+ validate = ValidateOp()
87
+
shapely/ops.pyc ADDED
Binary file
shapely/predicates.py ADDED
@@ -0,0 +1,24 @@
1
+ """
2
+ Support for GEOS spatial predicates
3
+ """
4
+
5
+ from shapely.geos import PredicateError, lgeos
6
+ from shapely.topology import Delegating
7
+
8
+ class BinaryPredicate(Delegating):
9
+ def __call__(self, this, other, *args):
10
+ self._validate(this)
11
+ self._validate(other)
12
+ return self.fn(this._geom, other._geom, *args)
13
+
14
+ class RelateOp(Delegating):
15
+ def __call__(self, this, other):
16
+ self._validate(this)
17
+ self._validate(other)
18
+ return self.fn(this._geom, other._geom)
19
+
20
+ class UnaryPredicate(Delegating):
21
+ def __call__(self, this):
22
+ self._validate(this)
23
+ return self.fn(this._geom)
24
+