shapely 1.3.3__cp34-none-win_amd64.whl

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 (95) hide show
  1. Shapely-1.3.3.data/data/shapely/_geos.pxi +52 -0
  2. Shapely-1.3.3.dist-info/DESCRIPTION.rst +505 -0
  3. Shapely-1.3.3.dist-info/METADATA +527 -0
  4. Shapely-1.3.3.dist-info/RECORD +95 -0
  5. Shapely-1.3.3.dist-info/WHEEL +5 -0
  6. Shapely-1.3.3.dist-info/metadata.json +1 -0
  7. Shapely-1.3.3.dist-info/top_level.txt +1 -0
  8. shapely/DLLs/geos.dll +0 -0
  9. shapely/DLLs/geos_c.dll +0 -0
  10. shapely/__init__.py +1 -0
  11. shapely/_geos.pxi +52 -0
  12. shapely/affinity.py +255 -0
  13. shapely/algorithms/__init__.py +0 -0
  14. shapely/algorithms/cga.py +16 -0
  15. shapely/coords.py +206 -0
  16. shapely/ctypes_declarations.py +455 -0
  17. shapely/examples/__init__.py +1 -0
  18. shapely/examples/dissolve.py +53 -0
  19. shapely/examples/geoms.py +51 -0
  20. shapely/examples/intersect.py +81 -0
  21. shapely/examples/world.py +21 -0
  22. shapely/ftools.py +78 -0
  23. shapely/geometry/__init__.py +20 -0
  24. shapely/geometry/base.py +797 -0
  25. shapely/geometry/collection.py +43 -0
  26. shapely/geometry/geo.py +75 -0
  27. shapely/geometry/linestring.py +298 -0
  28. shapely/geometry/multilinestring.py +156 -0
  29. shapely/geometry/multipoint.py +213 -0
  30. shapely/geometry/multipolygon.py +186 -0
  31. shapely/geometry/point.py +269 -0
  32. shapely/geometry/polygon.py +504 -0
  33. shapely/geometry/proxy.py +51 -0
  34. shapely/geos.py +732 -0
  35. shapely/impl.py +126 -0
  36. shapely/iterops.py +55 -0
  37. shapely/linref.py +26 -0
  38. shapely/ops.py +234 -0
  39. shapely/predicates.py +23 -0
  40. shapely/prepared.py +61 -0
  41. shapely/speedups/__init__.py +43 -0
  42. shapely/speedups/_speedups.c +5674 -0
  43. shapely/speedups/_speedups.pyd +0 -0
  44. shapely/tests/__init__.py +81 -0
  45. shapely/tests/binascii_hex.txt +47 -0
  46. shapely/tests/test_affinity.py +255 -0
  47. shapely/tests/test_box.py +24 -0
  48. shapely/tests/test_cga.py +37 -0
  49. shapely/tests/test_collection.py +29 -0
  50. shapely/tests/test_delegated.py +34 -0
  51. shapely/tests/test_dlls.py +20 -0
  52. shapely/tests/test_doctests.py +36 -0
  53. shapely/tests/test_emptiness.py +53 -0
  54. shapely/tests/test_equality.py +29 -0
  55. shapely/tests/test_geointerface.py +74 -0
  56. shapely/tests/test_geomseq.py +13 -0
  57. shapely/tests/test_getitem.py +125 -0
  58. shapely/tests/test_invalid_geometries.py +30 -0
  59. shapely/tests/test_iterops.py +47 -0
  60. shapely/tests/test_linear_referencing.py +72 -0
  61. shapely/tests/test_linemerge.py +52 -0
  62. shapely/tests/test_linestring.py +111 -0
  63. shapely/tests/test_locale.py +56 -0
  64. shapely/tests/test_mapping.py +13 -0
  65. shapely/tests/test_multilinestring.py +61 -0
  66. shapely/tests/test_multipoint.py +73 -0
  67. shapely/tests/test_multipolygon.py +72 -0
  68. shapely/tests/test_ndarrays.py +54 -0
  69. shapely/tests/test_operations.py +70 -0
  70. shapely/tests/test_operators.py +18 -0
  71. shapely/tests/test_persist.py +34 -0
  72. shapely/tests/test_pickle.py +22 -0
  73. shapely/tests/test_point.py +139 -0
  74. shapely/tests/test_polygon.py +186 -0
  75. shapely/tests/test_polygonize.py +49 -0
  76. shapely/tests/test_predicates.py +34 -0
  77. shapely/tests/test_prepared.py +31 -0
  78. shapely/tests/test_products_z.py +17 -0
  79. shapely/tests/test_singularity.py +19 -0
  80. shapely/tests/test_speedups.py +39 -0
  81. shapely/tests/test_styles.py +20 -0
  82. shapely/tests/test_transform.py +84 -0
  83. shapely/tests/test_union.py +72 -0
  84. shapely/tests/test_validation.py +12 -0
  85. shapely/tests/test_vectorized.py +107 -0
  86. shapely/tests/test_xy.py +17 -0
  87. shapely/tests/threading_test.py +40 -0
  88. shapely/topology.py +60 -0
  89. shapely/validation.py +8 -0
  90. shapely/vectorized/__init__.py +3 -0
  91. shapely/vectorized/_vectorized.c +20816 -0
  92. shapely/vectorized/_vectorized.pyd +0 -0
  93. shapely/vectorized/_vectorized.pyx +120 -0
  94. shapely/wkb.py +37 -0
  95. shapely/wkt.py +26 -0
@@ -0,0 +1,797 @@
1
+ """Base geometry class and utilities
2
+ """
3
+
4
+ import sys
5
+ from warnings import warn
6
+ from binascii import a2b_hex
7
+ from ctypes import pointer, c_size_t, c_char_p, c_void_p
8
+
9
+ from shapely.coords import CoordinateSequence
10
+ from shapely.ftools import wraps
11
+ from shapely.geos import lgeos, ReadingError
12
+ from shapely.geos import WKBWriter, WKTWriter
13
+ from shapely.impl import DefaultImplementation, delegated
14
+
15
+ if sys.version_info[0] < 3:
16
+ range = xrange
17
+
18
+ GEOMETRY_TYPES = [
19
+ 'Point',
20
+ 'LineString',
21
+ 'LinearRing',
22
+ 'Polygon',
23
+ 'MultiPoint',
24
+ 'MultiLineString',
25
+ 'MultiPolygon',
26
+ 'GeometryCollection',
27
+ ]
28
+
29
+
30
+ def dump_coords(geom):
31
+ """Dump coordinates of a geometry in the same order as data packing"""
32
+ if not isinstance(geom, BaseGeometry):
33
+ raise ValueError('Must be instance of a geometry class; found ' +
34
+ geom.__class__.__name__)
35
+ elif geom.type in ('Point', 'LineString', 'LinearRing'):
36
+ return geom.coords[:]
37
+ elif geom.type == 'Polygon':
38
+ return geom.exterior.coords[:] + [i.coords[:] for i in geom.interiors]
39
+ elif geom.type.startswith('Multi') or geom.type == 'GeometryCollection':
40
+ # Recursive call
41
+ return [dump_coords(part) for part in geom]
42
+ else:
43
+ raise ValueError('Unhandled geometry type: ' + repr(geom.type))
44
+
45
+
46
+ def geometry_type_name(g):
47
+ if g is None:
48
+ raise ValueError("Null geometry has no type")
49
+ return GEOMETRY_TYPES[lgeos.GEOSGeomTypeId(g)]
50
+
51
+
52
+ def geom_factory(g, parent=None):
53
+ # Abstract geometry factory for use with topological methods below
54
+ if not g:
55
+ raise ValueError("No Shapely geometry can be created from null value")
56
+ ob = BaseGeometry()
57
+ geom_type = geometry_type_name(g)
58
+ # TODO: check cost of dynamic import by profiling
59
+ mod = __import__(
60
+ 'shapely.geometry',
61
+ globals(),
62
+ locals(),
63
+ [geom_type],
64
+ )
65
+ ob.__class__ = getattr(mod, geom_type)
66
+ ob.__geom__ = g
67
+ ob.__p__ = parent
68
+ if lgeos.methods['has_z'](g):
69
+ ob._ndim = 3
70
+ else:
71
+ ob._ndim = 2
72
+ return ob
73
+
74
+
75
+ def geom_from_wkt(data):
76
+ warn("`geom_from_wkt` is deprecated. Use `geos.wkt_reader.read(data)`.",
77
+ DeprecationWarning)
78
+ if sys.version_info[0] >= 3:
79
+ data = data.encode('ascii')
80
+ geom = lgeos.GEOSGeomFromWKT(c_char_p(data))
81
+ if not geom:
82
+ raise ReadingError(
83
+ "Could not create geometry because of errors while reading input.")
84
+ return geom_factory(geom)
85
+
86
+
87
+ def geom_to_wkt(ob):
88
+ warn("`geom_to_wkt` is deprecated. Use `geos.wkt_writer.write(ob)`.",
89
+ DeprecationWarning)
90
+ if ob is None or ob._geom is None:
91
+ raise ValueError("Null geometry supports no operations")
92
+ return lgeos.GEOSGeomToWKT(ob._geom)
93
+
94
+
95
+ def deserialize_wkb(data):
96
+ geom = lgeos.GEOSGeomFromWKB_buf(c_char_p(data), c_size_t(len(data)))
97
+ if not geom:
98
+ raise ReadingError(
99
+ "Could not create geometry because of errors while reading input.")
100
+ return geom
101
+
102
+
103
+ def geom_from_wkb(data):
104
+ warn("`geom_from_wkb` is deprecated. Use `geos.wkb_reader.read(data)`.",
105
+ DeprecationWarning)
106
+ return geom_factory(deserialize_wkb(data))
107
+
108
+
109
+ def geom_to_wkb(ob):
110
+ warn("`geom_to_wkb` is deprecated. Use `geos.wkb_writer.write(ob)`.",
111
+ DeprecationWarning)
112
+ if ob is None or ob._geom is None:
113
+ raise ValueError("Null geometry supports no operations")
114
+ size = c_size_t()
115
+ return lgeos.GEOSGeomToWKB_buf(c_void_p(ob._geom), pointer(size))
116
+
117
+
118
+ def exceptNull(func):
119
+ """Decorator which helps avoid GEOS operations on null pointers."""
120
+ @wraps(func)
121
+ def wrapper(*args, **kwargs):
122
+ if not args[0]._geom or args[0].is_empty:
123
+ raise ValueError("Null/empty geometry supports no operations")
124
+ return func(*args, **kwargs)
125
+ return wrapper
126
+
127
+
128
+ class CAP_STYLE(object):
129
+ round = 1
130
+ flat = 2
131
+ square = 3
132
+
133
+
134
+ class JOIN_STYLE(object):
135
+ round = 1
136
+ mitre = 2
137
+ bevel = 3
138
+
139
+ EMPTY = deserialize_wkb(a2b_hex(b'010700000000000000'))
140
+
141
+
142
+ class BaseGeometry(object):
143
+ """
144
+ Provides GEOS spatial predicates and topological operations.
145
+
146
+ """
147
+
148
+ # Attributes
149
+ # ----------
150
+ # __geom__ : c_void_p
151
+ # Cached ctypes pointer to GEOS geometry. Not to be accessed.
152
+ # _geom : c_void_p
153
+ # Property by which the GEOS geometry is accessed.
154
+ # __p__ : object
155
+ # Parent (Shapely) geometry
156
+ # _ctypes_data : object
157
+ # Cached ctypes data buffer
158
+ # _ndim : int
159
+ # Number of dimensions (2 or 3, generally)
160
+ # _crs : object
161
+ # Coordinate reference system. Available for Shapely extensions, but
162
+ # not implemented here.
163
+ # _other_owned : bool
164
+ # True if this object's GEOS geometry is owned by another as in the
165
+ # case of a multipart geometry member.
166
+ __geom__ = EMPTY
167
+ __p__ = None
168
+ _ctypes_data = None
169
+ _ndim = None
170
+ _crs = None
171
+ _other_owned = False
172
+
173
+ # Backend config
174
+ impl = DefaultImplementation
175
+
176
+ @property
177
+ def _is_empty(self):
178
+ return self.__geom__ in [EMPTY, None]
179
+
180
+ # a reference to the so/dll proxy to preserve access during clean up
181
+ _lgeos = lgeos
182
+
183
+ def empty(self, val=EMPTY):
184
+ # TODO: defer cleanup to the implementation. We shouldn't be
185
+ # explicitly calling a lgeos method here.
186
+ if not self._is_empty and not self._other_owned and self.__geom__:
187
+ try:
188
+ self._lgeos.GEOSGeom_destroy(self.__geom__)
189
+ except AttributeError:
190
+ pass # _lgeos might be empty on shutdown
191
+ self.__geom__ = val
192
+
193
+ def __del__(self):
194
+ self.empty(val=None)
195
+ self.__p__ = None
196
+
197
+ def __str__(self):
198
+ return self.wkt
199
+
200
+ # To support pickling
201
+ def __reduce__(self):
202
+ return (self.__class__, (), self.wkb)
203
+
204
+ def __setstate__(self, state):
205
+ self.empty()
206
+ self.__geom__ = deserialize_wkb(state)
207
+ if lgeos.methods['has_z'](self.__geom__):
208
+ self._ndim = 3
209
+ else:
210
+ self._ndim = 2
211
+
212
+ @property
213
+ def _geom(self):
214
+ return self.__geom__
215
+
216
+ @_geom.setter
217
+ def _geom(self, val):
218
+ self.empty()
219
+ self.__geom__ = val
220
+
221
+ # Operators
222
+ # ---------
223
+
224
+ def __and__(self, other):
225
+ return self.intersection(other)
226
+
227
+ def __or__(self, other):
228
+ return self.union(other)
229
+
230
+ def __sub__(self, other):
231
+ return self.difference(other)
232
+
233
+ def __xor__(self, other):
234
+ return self.symmetric_difference(other)
235
+
236
+ # Array and ctypes interfaces
237
+ # ---------------------------
238
+
239
+ @property
240
+ def ctypes(self):
241
+ """Return ctypes buffer"""
242
+ raise NotImplementedError
243
+
244
+ @property
245
+ def array_interface_base(self):
246
+ if sys.byteorder == 'little':
247
+ typestr = '<f8'
248
+ elif sys.byteorder == 'big':
249
+ typestr = '>f8'
250
+ else:
251
+ raise ValueError(
252
+ "Unsupported byteorder: neither little nor big-endian")
253
+ return {
254
+ 'version': 3,
255
+ 'typestr': typestr,
256
+ 'data': self.ctypes,
257
+ }
258
+
259
+ @property
260
+ def __array_interface__(self):
261
+ """Provide the Numpy array protocol."""
262
+ raise NotImplementedError
263
+
264
+ # Coordinate access
265
+ # -----------------
266
+
267
+ def _get_coords(self):
268
+ """Access to geometry's coordinates (CoordinateSequence)"""
269
+ if self.is_empty:
270
+ return []
271
+ return CoordinateSequence(self)
272
+
273
+ def _set_coords(self, ob):
274
+ raise NotImplementedError(
275
+ "set_coords must be provided by derived classes")
276
+
277
+ coords = property(_get_coords, _set_coords)
278
+
279
+ @property
280
+ def xy(self):
281
+ """Separate arrays of X and Y coordinate values"""
282
+ raise NotImplementedError
283
+
284
+ # Python feature protocol
285
+
286
+ @property
287
+ def __geo_interface__(self):
288
+ """Dictionary representation of the geometry"""
289
+ raise NotImplementedError
290
+
291
+ # Type of geometry and its representations
292
+ # ----------------------------------------
293
+
294
+ def geometryType(self):
295
+ return geometry_type_name(self._geom)
296
+
297
+ @property
298
+ def type(self):
299
+ return self.geometryType()
300
+
301
+ def to_wkb(self):
302
+ warn("`to_wkb` is deprecated. Use the `wkb` property.",
303
+ DeprecationWarning)
304
+ return geom_to_wkb(self)
305
+
306
+ def to_wkt(self):
307
+ warn("`to_wkt` is deprecated. Use the `wkt` property.",
308
+ DeprecationWarning)
309
+ return geom_to_wkt(self)
310
+
311
+ @property
312
+ def wkt(self, **kw):
313
+ """WKT representation of the geometry"""
314
+ return WKTWriter(lgeos, **kw).write(self)
315
+
316
+ @property
317
+ def wkb(self):
318
+ """WKB representation of the geometry"""
319
+ return WKBWriter(lgeos).write(self)
320
+
321
+ @property
322
+ def wkb_hex(self):
323
+ """WKB hex representation of the geometry"""
324
+ return WKBWriter(lgeos).write_hex(self)
325
+
326
+ def svg(self, scale_factor=1.):
327
+ """
328
+ SVG representation of the geometry. Scale factor is multiplied by
329
+ the size of the SVG symbol so it can be scaled consistently for a
330
+ consistent appearance based on the canvas size.
331
+ """
332
+ raise NotImplementedError
333
+
334
+ def _repr_svg_(self):
335
+ """SVG representation for iPython notebook"""
336
+ #Pick an arbitrary size for the SVG canvas
337
+
338
+
339
+ xmin, ymin, xmax, ymax = self.buffer(1).bounds
340
+ x_size = min([max([100., xmax - xmin]), 300])
341
+ y_size = min([max([100., ymax - ymin]), 300])
342
+ try:
343
+ scale_factor = max([xmax - xmin, ymax - ymin]) / max([x_size, y_size])
344
+ except ZeroDivisionError:
345
+ scale_factor = 1
346
+ buffered_box = "{0} {1} {2} {3}".format(xmin, ymin, xmax - xmin, ymax - ymin)
347
+ return """<svg
348
+ preserveAspectRatio="xMinYMin meet"
349
+ viewBox="{0}"
350
+ width="{1}"
351
+ height="{2}"
352
+ transform="translate(0, {1}),scale(1, -1)">
353
+ {3}
354
+ </svg>""".format(buffered_box, x_size, y_size, self.svg(scale_factor))
355
+
356
+ @property
357
+ def geom_type(self):
358
+ """Name of the geometry's type, such as 'Point'"""
359
+ return self.geometryType()
360
+
361
+ # Real-valued properties and methods
362
+ # ----------------------------------
363
+
364
+ @property
365
+ def area(self):
366
+ """Unitless area of the geometry (float)"""
367
+ return self.impl['area'](self)
368
+
369
+ def distance(self, other):
370
+ """Unitless distance to other geometry (float)"""
371
+ return self.impl['distance'](self, other)
372
+
373
+ @property
374
+ def length(self):
375
+ """Unitless length of the geometry (float)"""
376
+ return self.impl['length'](self)
377
+
378
+ # Topological properties
379
+ # ----------------------
380
+
381
+ @property
382
+ def boundary(self):
383
+ """Returns a lower dimension geometry that bounds the object
384
+
385
+ The boundary of a polygon is a line, the boundary of a line is a
386
+ collection of points. The boundary of a point is an empty (null)
387
+ collection.
388
+ """
389
+ return geom_factory(self.impl['boundary'](self))
390
+
391
+ @property
392
+ def bounds(self):
393
+ """Returns minimum bounding region (minx, miny, maxx, maxy)"""
394
+ if self.is_empty:
395
+ return ()
396
+ else:
397
+ return self.impl['bounds'](self)
398
+
399
+ @property
400
+ def centroid(self):
401
+ """Returns the geometric center of the object"""
402
+ return geom_factory(self.impl['centroid'](self))
403
+
404
+ @delegated
405
+ def representative_point(self):
406
+ """Returns a point guaranteed to be within the object, cheaply."""
407
+ return geom_factory(self.impl['representative_point'](self))
408
+
409
+ @property
410
+ def convex_hull(self):
411
+ """Imagine an elastic band stretched around the geometry: that's a
412
+ convex hull, more or less
413
+
414
+ The convex hull of a three member multipoint, for example, is a
415
+ triangular polygon.
416
+ """
417
+ return geom_factory(self.impl['convex_hull'](self))
418
+
419
+ @property
420
+ def envelope(self):
421
+ """A figure that envelopes the geometry"""
422
+ return geom_factory(self.impl['envelope'](self))
423
+
424
+ def buffer(self, distance, resolution=16, quadsegs=None,
425
+ cap_style=CAP_STYLE.round, join_style=JOIN_STYLE.round,
426
+ mitre_limit=5.0):
427
+ """Returns a geometry with an envelope at a distance from the object's
428
+ envelope
429
+
430
+ A negative distance has a "shrink" effect. A zero distance may be used
431
+ to "tidy" a polygon. The resolution of the buffer around each vertex of
432
+ the object increases by increasing the resolution keyword parameter
433
+ or second positional parameter. Note: the use of a `quadsegs` parameter
434
+ is deprecated and will be gone from the next major release.
435
+
436
+ The styles of caps are: CAP_STYLE.round (1), CAP_STYLE.flat (2), and
437
+ CAP_STYLE.square (3).
438
+
439
+ The styles of joins between offset segments are: JOIN_STYLE.round (1),
440
+ JOIN_STYLE.mitre (2), and JOIN_STYLE.bevel (3).
441
+
442
+ The mitre limit ratio is used for very sharp corners. The mitre ratio
443
+ is the ratio of the distance from the corner to the end of the mitred
444
+ offset corner. When two line segments meet at a sharp angle, a miter
445
+ join will extend the original geometry. To prevent unreasonable
446
+ geometry, the mitre limit allows controlling the maximum length of the
447
+ join corner. Corners with a ratio which exceed the limit will be
448
+ beveled.
449
+
450
+ Example:
451
+
452
+ >>> from shapely.wkt import loads
453
+ >>> g = loads('POINT (0.0 0.0)')
454
+ >>> g.buffer(1.0).area # 16-gon approx of a unit radius circle
455
+ 3.1365484905459389
456
+ >>> g.buffer(1.0, 128).area # 128-gon approximation
457
+ 3.1415138011443009
458
+ >>> g.buffer(1.0, 3).area # triangle approximation
459
+ 3.0
460
+ >>> list(g.buffer(1.0, cap_style='square').exterior.coords)
461
+ [(1.0, 1.0), (1.0, -1.0), (-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)]
462
+ >>> g.buffer(1.0, cap_style='square').area
463
+ 4.0
464
+ """
465
+ if quadsegs is not None:
466
+ warn(
467
+ "The `quadsegs` argument is deprecated. Use `resolution`.",
468
+ DeprecationWarning)
469
+ res = quadsegs
470
+ else:
471
+ res = resolution
472
+ if mitre_limit == 0.0:
473
+ raise ValueError(
474
+ 'Cannot compute offset from zero-length line segment')
475
+ if cap_style == CAP_STYLE.round and join_style == JOIN_STYLE.round:
476
+ return geom_factory(self.impl['buffer'](self, distance, res))
477
+
478
+ if 'buffer_with_style' not in self.impl:
479
+ raise NotImplementedError("Styled buffering not available for "
480
+ "GEOS versions < 3.2.")
481
+
482
+ return geom_factory(self.impl['buffer_with_style'](self, distance, res,
483
+ cap_style,
484
+ join_style,
485
+ mitre_limit))
486
+
487
+ @delegated
488
+ def simplify(self, tolerance, preserve_topology=True):
489
+ """Returns a simplified geometry produced by the Douglas-Puecker
490
+ algorithm
491
+
492
+ Coordinates of the simplified geometry will be no more than the
493
+ tolerance distance from the original. Unless the topology preserving
494
+ option is used, the algorithm may produce self-intersecting or
495
+ otherwise invalid geometries.
496
+ """
497
+ if preserve_topology:
498
+ op = self.impl['topology_preserve_simplify']
499
+ else:
500
+ op = self.impl['simplify']
501
+ return geom_factory(op(self, tolerance))
502
+
503
+ # Binary operations
504
+ # -----------------
505
+
506
+ def difference(self, other):
507
+ """Returns the difference of the geometries"""
508
+ return geom_factory(self.impl['difference'](self, other))
509
+
510
+ def intersection(self, other):
511
+ """Returns the intersection of the geometries"""
512
+ return geom_factory(self.impl['intersection'](self, other))
513
+
514
+ def symmetric_difference(self, other):
515
+ """Returns the symmetric difference of the geometries
516
+ (Shapely geometry)"""
517
+ return geom_factory(self.impl['symmetric_difference'](self, other))
518
+
519
+ def union(self, other):
520
+ """Returns the union of the geometries (Shapely geometry)"""
521
+ return geom_factory(self.impl['union'](self, other))
522
+
523
+ # Unary predicates
524
+ # ----------------
525
+
526
+ @property
527
+ def has_z(self):
528
+ """True if the geometry's coordinate sequence(s) have z values (are
529
+ 3-dimensional)"""
530
+ return bool(self.impl['has_z'](self))
531
+
532
+ @property
533
+ def is_empty(self):
534
+ """True if the set of points in this geometry is empty, else False"""
535
+ return (self._geom is None) or bool(self.impl['is_empty'](self))
536
+
537
+ @property
538
+ def is_ring(self):
539
+ """True if the geometry is a closed ring, else False"""
540
+ return bool(self.impl['is_ring'](self))
541
+
542
+ @property
543
+ def is_simple(self):
544
+ """True if the geometry is simple, meaning that any self-intersections
545
+ are only at boundary points, else False"""
546
+ return bool(self.impl['is_simple'](self))
547
+
548
+ @property
549
+ def is_valid(self):
550
+ """True if the geometry is valid (definition depends on sub-class),
551
+ else False"""
552
+ return bool(self.impl['is_valid'](self))
553
+
554
+ # Binary predicates
555
+ # -----------------
556
+
557
+ def relate(self, other):
558
+ """Returns the DE-9IM intersection matrix for the two geometries
559
+ (string)"""
560
+ return self.impl['relate'](self, other)
561
+
562
+ def contains(self, other):
563
+ """Returns True if the geometry contains the other, else False"""
564
+ return bool(self.impl['contains'](self, other))
565
+
566
+ def crosses(self, other):
567
+ """Returns True if the geometries cross, else False"""
568
+ return bool(self.impl['crosses'](self, other))
569
+
570
+ def disjoint(self, other):
571
+ """Returns True if geometries are disjoint, else False"""
572
+ return bool(self.impl['disjoint'](self, other))
573
+
574
+ def equals(self, other):
575
+ """Returns True if geometries are equal, else False"""
576
+ return bool(self.impl['equals'](self, other))
577
+
578
+ def intersects(self, other):
579
+ """Returns True if geometries intersect, else False"""
580
+ return bool(self.impl['intersects'](self, other))
581
+
582
+ def overlaps(self, other):
583
+ """Returns True if geometries overlap, else False"""
584
+ return bool(self.impl['overlaps'](self, other))
585
+
586
+ def touches(self, other):
587
+ """Returns True if geometries touch, else False"""
588
+ return bool(self.impl['touches'](self, other))
589
+
590
+ def within(self, other):
591
+ """Returns True if geometry is within the other, else False"""
592
+ return bool(self.impl['within'](self, other))
593
+
594
+ def equals_exact(self, other, tolerance):
595
+ """Returns True if geometries are equal to within a specified
596
+ tolerance"""
597
+ # return BinaryPredicateOp('equals_exact', self)(other, tolerance)
598
+ return bool(self.impl['equals_exact'](self, other, tolerance))
599
+
600
+ def almost_equals(self, other, decimal=6):
601
+ """Returns True if geometries are equal at all coordinates to a
602
+ specified decimal place"""
603
+ return self.equals_exact(other, 0.5 * 10**(-decimal))
604
+
605
+ # Linear referencing
606
+ # ------------------
607
+
608
+ @delegated
609
+ def project(self, other, normalized=False):
610
+ """Returns the distance along this geometry to a point nearest the
611
+ specified point
612
+
613
+ If the normalized arg is True, return the distance normalized to the
614
+ length of the linear geometry.
615
+ """
616
+ if normalized:
617
+ op = self.impl['project_normalized']
618
+ else:
619
+ op = self.impl['project']
620
+ return op(self, other)
621
+
622
+ @delegated
623
+ def interpolate(self, distance, normalized=False):
624
+ """Return a point at the specified distance along a linear geometry
625
+
626
+ If the normalized arg is True, the distance will be interpreted as a
627
+ fraction of the geometry's length.
628
+ """
629
+ if normalized:
630
+ op = self.impl['interpolate_normalized']
631
+ else:
632
+ op = self.impl['interpolate']
633
+ return geom_factory(op(self, distance))
634
+
635
+
636
+ class BaseMultipartGeometry(BaseGeometry):
637
+
638
+ def shape_factory(self, *args):
639
+ # Factory for part instances, usually a geometry class
640
+ raise NotImplementedError("To be implemented by derived classes")
641
+
642
+ @property
643
+ def ctypes(self):
644
+ raise NotImplementedError(
645
+ "Multi-part geometries have no ctypes representations")
646
+
647
+ @property
648
+ def __array_interface__(self):
649
+ """Provide the Numpy array protocol."""
650
+ raise NotImplementedError("Multi-part geometries do not themselves "
651
+ "provide the array interface")
652
+
653
+ def _get_coords(self):
654
+ raise NotImplementedError("Sub-geometries may have coordinate "
655
+ "sequences, but collections do not")
656
+
657
+ def _set_coords(self, ob):
658
+ raise NotImplementedError("Sub-geometries may have coordinate "
659
+ "sequences, but collections do not")
660
+
661
+ @property
662
+ def coords(self):
663
+ raise NotImplementedError(
664
+ "Multi-part geometries do not provide a coordinate sequence")
665
+
666
+ @property
667
+ def geoms(self):
668
+ if self.is_empty:
669
+ return []
670
+ return GeometrySequence(self, self.shape_factory)
671
+
672
+ def __iter__(self):
673
+ if not self.is_empty:
674
+ return iter(self.geoms)
675
+ else:
676
+ return iter([])
677
+
678
+ def __len__(self):
679
+ if not self.is_empty:
680
+ return len(self.geoms)
681
+ else:
682
+ return 0
683
+
684
+ def __getitem__(self, index):
685
+ if not self.is_empty:
686
+ return self.geoms[index]
687
+ else:
688
+ return ()[index]
689
+
690
+ def svg(self, scale_factor=1.):
691
+ """
692
+ SVG representation of the geometry. Scale factor is multiplied by
693
+ the size of the SVG symbol so it can be scaled consistently for a
694
+ consistent appearance based on the canvas size.
695
+ """
696
+ return "\n".join([g.svg(scale_factor) for g in self])
697
+
698
+
699
+ class GeometrySequence(object):
700
+ """
701
+ Iterative access to members of a homogeneous multipart geometry.
702
+ """
703
+
704
+ # Attributes
705
+ # ----------
706
+ # _factory : callable
707
+ # Returns instances of Shapely geometries
708
+ # _geom : c_void_p
709
+ # Ctypes pointer to the parent's GEOS geometry
710
+ # _ndim : int
711
+ # Number of dimensions (2 or 3, generally)
712
+ # __p__ : object
713
+ # Parent (Shapely) geometry
714
+ shape_factory = None
715
+ _geom = None
716
+ __p__ = None
717
+ _ndim = None
718
+
719
+ def __init__(self, parent, type):
720
+ self.shape_factory = type
721
+ self.__p__ = parent
722
+
723
+ def _update(self):
724
+ self._geom = self.__p__._geom
725
+ self._ndim = self.__p__._ndim
726
+
727
+ def _get_geom_item(self, i):
728
+ g = self.shape_factory()
729
+ g._other_owned = True
730
+ g._geom = lgeos.GEOSGetGeometryN(self._geom, i)
731
+ g._ndim = self._ndim
732
+ g.__p__ = self
733
+ return g
734
+
735
+ def __iter__(self):
736
+ self._update()
737
+ for i in range(self.__len__()):
738
+ yield self._get_geom_item(i)
739
+
740
+ def __len__(self):
741
+ self._update()
742
+ return lgeos.GEOSGetNumGeometries(self._geom)
743
+
744
+ def __getitem__(self, key):
745
+ self._update()
746
+ m = self.__len__()
747
+ if isinstance(key, int):
748
+ if key + m < 0 or key >= m:
749
+ raise IndexError("index out of range")
750
+ if key < 0:
751
+ i = m + key
752
+ else:
753
+ i = key
754
+ return self._get_geom_item(i)
755
+ elif isinstance(key, slice):
756
+ if type(self) == HeterogeneousGeometrySequence:
757
+ raise TypeError(
758
+ "Heterogenous geometry collections are not sliceable")
759
+ res = []
760
+ start, stop, stride = key.indices(m)
761
+ for i in range(start, stop, stride):
762
+ res.append(self._get_geom_item(i))
763
+ return type(self.__p__)(res or None)
764
+ else:
765
+ raise TypeError("key must be an index or slice")
766
+
767
+ @property
768
+ def _longest(self):
769
+ max = 0
770
+ for g in iter(self):
771
+ l = len(g.coords)
772
+ if l > max:
773
+ max = l
774
+
775
+
776
+ class HeterogeneousGeometrySequence(GeometrySequence):
777
+ """
778
+ Iterative access to a heterogeneous sequence of geometries.
779
+ """
780
+
781
+ def __init__(self, parent):
782
+ super(HeterogeneousGeometrySequence, self).__init__(parent, None)
783
+
784
+ def _get_geom_item(self, i):
785
+ sub = lgeos.GEOSGetGeometryN(self._geom, i)
786
+ g = geom_factory(sub, parent=self)
787
+ g._other_owned = True
788
+ return g
789
+
790
+
791
+ def _test():
792
+ """Test runner"""
793
+ import doctest
794
+ doctest.testmod()
795
+
796
+ if __name__ == "__main__":
797
+ _test()