forked from geopandas/geopandas
/
geoseries.py
317 lines (258 loc) · 10.2 KB
/
geoseries.py
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
from functools import partial
import json
from warnings import warn
import numpy as np
from pandas import Series, DataFrame
from pandas.core.indexing import _NDFrameIndexer
import pyproj
from shapely.geometry import box, shape, Polygon, Point
from shapely.geometry.collection import GeometryCollection
from shapely.geometry.base import BaseGeometry
from shapely.ops import transform
from geopandas.plotting import plot_series
from geopandas.base import GeoPandasBase, _series_unary_op
def _is_empty(x):
try:
return x.is_empty
except:
return False
class _CoordinateIndexer(_NDFrameIndexer):
""" Indexing by coordinate slices """
def _getitem_tuple(self, tup):
obj = self.obj
xs, ys = tup
# handle numeric values as x and/or y coordinate index
if type(xs) is not slice:
xs = slice(xs, xs)
if type(ys) is not slice:
ys = slice(ys, ys)
# don't know how to handle step; should this raise?
if xs.step is not None or ys.step is not None:
warn("Ignoring step - full interval is used.")
xmin, ymin, xmax, ymax = obj.total_bounds
bbox = box(xs.start or xmin,
ys.start or ymin,
xs.stop or xmax,
ys.stop or ymax)
idx = obj.intersects(bbox)
return obj[idx]
class GeoSeries(GeoPandasBase, Series):
"""A Series object designed to store shapely geometry objects."""
_metadata = ['name', 'crs']
def __new__(cls, *args, **kwargs):
kwargs.pop('crs', None)
arr = Series.__new__(cls)
if type(arr) is GeoSeries:
return arr
else:
return arr.view(GeoSeries)
def __init__(self, *args, **kwargs):
# fix problem for scalar geometries passed
if len(args) == 1 and isinstance(args[0], BaseGeometry):
args = ([args[0]],)
crs = kwargs.pop('crs', None)
super(GeoSeries, self).__init__(*args, **kwargs)
self.crs = crs
self._invalidate_sindex()
def append(self, *args, **kwargs):
return self._wrapped_pandas_method('append', *args, **kwargs)
@property
def geometry(self):
return self
@property
def x(self):
"""Return the x location of point geometries in a GeoSeries"""
if (self.geom_type == "Point").all():
return _series_unary_op(self, 'x', null_value=np.nan)
else:
message = "x attribute access only provided for Point geometries"
raise ValueError(message)
@property
def y(self):
"""Return the y location of point geometries in a GeoSeries"""
if (self.geom_type == "Point").all():
return _series_unary_op(self, 'y', null_value=np.nan)
else:
message = "y attribute access only provided for Point geometries"
raise ValueError(message)
@classmethod
def from_file(cls, filename, **kwargs):
"""
Alternate constructor to create a GeoSeries from a file
Parameters
----------
filename : str
File path or file handle to read from. Depending on which kwargs
are included, the content of filename may vary, see:
http://toblerity.github.io/fiona/README.html#usage
for usage details.
kwargs : key-word arguments
These arguments are passed to fiona.open, and can be used to
access multi-layer data, data stored within archives (zip files),
etc.
"""
import fiona
geoms = []
with fiona.open(filename, **kwargs) as f:
crs = f.crs
for rec in f:
geoms.append(shape(rec['geometry']))
g = GeoSeries(geoms)
g.crs = crs
return g
@property
def __geo_interface__(self):
"""Returns a GeoSeries as a python feature collection
"""
from geopandas import GeoDataFrame
return GeoDataFrame({'geometry': self}).__geo_interface__
def to_file(self, filename, driver="ESRI Shapefile", **kwargs):
from geopandas import GeoDataFrame
data = GeoDataFrame({"geometry": self,
"id":self.index.values},
index=self.index)
data.crs = self.crs
data.to_file(filename, driver, **kwargs)
#
# Implement pandas methods
#
@property
def _constructor(self):
return GeoSeries
def _wrapped_pandas_method(self, mtd, *args, **kwargs):
"""Wrap a generic pandas method to ensure it returns a GeoSeries"""
val = getattr(super(GeoSeries, self), mtd)(*args, **kwargs)
if type(val) == Series:
val.__class__ = GeoSeries
val.crs = self.crs
val._invalidate_sindex()
return val
def __getitem__(self, key):
return self._wrapped_pandas_method('__getitem__', key)
def sort_index(self, *args, **kwargs):
return self._wrapped_pandas_method('sort_index', *args, **kwargs)
def take(self, *args, **kwargs):
return self._wrapped_pandas_method('take', *args, **kwargs)
def select(self, *args, **kwargs):
return self._wrapped_pandas_method('select', *args, **kwargs)
@property
def _can_hold_na(self):
return False
def __finalize__(self, other, method=None, **kwargs):
""" propagate metadata from other to self """
# NOTE: backported from pandas master (upcoming v0.13)
for name in self._metadata:
object.__setattr__(self, name, getattr(other, name, None))
return self
def copy(self, order='C'):
"""
Make a copy of this GeoSeries object
Parameters
----------
deep : boolean, default True
Make a deep copy, i.e. also copy data
Returns
-------
copy : GeoSeries
"""
# FIXME: this will likely be unnecessary in pandas >= 0.13
return GeoSeries(self.values.copy(order), index=self.index,
name=self.name).__finalize__(self)
def isnull(self):
"""Null values in a GeoSeries are represented by empty geometric objects"""
non_geo_null = super(GeoSeries, self).isnull()
val = self.apply(_is_empty)
return np.logical_or(non_geo_null, val)
def fillna(self, value=None, method=None, inplace=False,
**kwargs):
"""Fill NA/NaN values with a geometry (empty polygon by default).
"method" is currently not implemented for pandas <= 0.12.
"""
if value is None:
value = Point()
return super(GeoSeries, self).fillna(value=value, method=method,
inplace=inplace, **kwargs)
def align(self, other, join='outer', level=None, copy=True,
fill_value=None, **kwargs):
if fill_value is None:
fill_value = Point()
left, right = super(GeoSeries, self).align(other, join=join,
level=level, copy=copy,
fill_value=fill_value,
**kwargs)
if isinstance(other, GeoSeries):
return GeoSeries(left), GeoSeries(right)
else: # It is probably a Series, let's keep it that way
return GeoSeries(left), right
def __contains__(self, other):
"""Allow tests of the form "geom in s"
Tests whether a GeoSeries contains a geometry.
Note: This is not the same as the geometric method "contains".
"""
if isinstance(other, BaseGeometry):
return np.any(self.geom_equals(other))
else:
return False
def plot(self, *args, **kwargs):
return plot_series(self, *args, **kwargs)
plot.__doc__ = plot_series.__doc__
#
# Additional methods
#
def to_crs(self, crs=None, epsg=None):
"""Transform geometries to a new coordinate reference system
This method will transform all points in all objects. It has
no notion or projecting entire geometries. All segments
joining points are assumed to be lines in the current
projection, not geodesics. Objects crossing the dateline (or
other projection boundary) will have undesirable behavior.
`to_crs` passes the `crs` argument to the `Proj` function from the
`pyproj` library (with the option `preserve_units=True`). It can
therefore accept proj4 projections in any format
supported by `Proj`, including dictionaries, or proj4 strings.
"""
from fiona.crs import from_epsg
if self.crs is None:
raise ValueError('Cannot transform naive geometries. '
'Please set a crs on the object first.')
if crs is None:
try:
crs = from_epsg(epsg)
except TypeError:
raise TypeError('Must set either crs or epsg for output.')
proj_in = pyproj.Proj(self.crs, preserve_units=True)
proj_out = pyproj.Proj(crs, preserve_units=True)
project = partial(pyproj.transform, proj_in, proj_out)
result = self.apply(lambda geom: transform(project, geom))
result.__class__ = GeoSeries
result.crs = crs
result._invalidate_sindex()
return result
def to_json(self, **kwargs):
"""
Returns a GeoJSON string representation of the GeoSeries.
Parameters
----------
*kwargs* that will be passed to json.dumps().
"""
return json.dumps(self.__geo_interface__, **kwargs)
#
# Implement standard operators for GeoSeries
#
def __xor__(self, other):
"""Implement ^ operator as for builtin set type"""
return self.symmetric_difference(other)
def __or__(self, other):
"""Implement | operator as for builtin set type"""
return self.union(other)
def __and__(self, other):
"""Implement & operator as for builtin set type"""
return self.intersection(other)
def __sub__(self, other):
"""Implement - operator as for builtin set type"""
return self.difference(other)
GeoSeries._create_indexer('cx', _CoordinateIndexer)
try:
from ._geoseries import *
except ImportError:
pass