-
Notifications
You must be signed in to change notification settings - Fork 44
/
02-spatial-data.qmd
377 lines (260 loc) · 13.9 KB
/
02-spatial-data.qmd
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
# Geographic data in Python {#spatial-class}
## Introduction
In this chapter, we introduce the key Python packages (and data structures) for working with the two major types of spatial data, namely:
* **shapely** and **geopandas** --- for working with vector layers
* **rasterio** and **xarray** --- for working with rasters
As we will see later on, **shapely** and **geopandas** are related:
* **shapely** is a "low-level" package for working with individual vector geometry objects
* **geopandas** is a "high-level" package for working with geometry columns (`GeoSeries` objects), which internally contain **shapely** geometries, and vector layers (`GeoDataFrame` objects)
While **geopandas** (including its **shapely** dependency), at present, comprises a ubiquitous comprehensive approach for working with vector layers in Python, this is not the case for rasters.
Work with rasters in Python is much less unified.
There are several alternative packages, each with its own advantages and disadvantages.
We focus on the two most comprehensive and fundamental packages, namely:
* **rasterio** --- a spatial-oriented package, focused on "simple" raster formats (such as GeoTIFF), representing a raster using a combination of a `numpy` array, and a metadata object (`dict`) specifying the spatial referencing of the array
* **xarray** --- A general-purpose package for working with labeled arrays, thus advantageous for processing "complex" raster format (such as NetCDF), representing a raster using its own native classes, namely `xarray.Dataset` and `xarray.DataArray`
## Vector data
### Introduction
When introducing the packages for working with vector layers in Python, we are going to go from the complex class (vector layer), through the intermediate (geometry column), to the simple (geometry).
As we will see, the three classes are hierarchical, meaning that the complex encompasses the simple:
* A vector layer (class `GeoDataFrame`) contains a geometry column (class `GeoSeries`) as one of the columns
* A geometry column (class `GeoSeries`) is composed of individual geometries (class `shapely`)
The first two classes (`GeoDataFrame` and `GeoSeries`) are defined in package **geopandas**.
The third class is defined in package **shapely**, which deals with individual geometries, and comprises on of the dependencies of the **geopandas** package.
### Vector layers
The typical data structure for vector data is a vector layer.
There are several methods to work with vector layers in Python, ranging from low-level (e.g., **fiona**) to high-level (**geopandas**).
In this book, we focus on **geopandas**.
Before we begin, we need to import the **geopandas** package, conventionally as `gpd`:
```{python}
import geopandas as gpd
```
We will also limit the maximum number of printed rows to four, to save space, using the `"display.max_rows"` option of **pandas**:
```{python}
import pandas as pd
pd.set_option("display.max_rows", 4)
```
Most often, we import an existing vector layer from a file, such as a Shapefile or a GeoPackage file.
```{python}
dat = gpd.read_file("data/world.gpkg")
```
The result is a `GeoDataFrame`:
```{python}
type(dat)
```
The `GeoDataFrame` class is an extension of the `DataFrame` class.
Thus, we can treat a vector layer as a table and process it using the ordinary, i.e., non-spatial, **pandas** methods.
For example, the following expression creates a subset with just the country name and the geometry (see below):
```{python}
dat = dat[["name_long", "geometry"]]
dat
```
The following expression creates a subset based on a condition, including just `"Egypt"`:
```{python}
dat[dat["name_long"] == "Egypt"]
```
Finally, to get a sense of the spatial component of the vector layer, it can be plotted using the `.plot` method, as follows:
```{python}
dat.plot();
```
```{python}
#| eval: false
# Todo: eval when fixed
import
lot.pandas
dat.hvplot()
```
### Geometry columns
One of the columns in a `GeoDataFrame` is a geometry column, of class `GeoSeries`.
The geometry column contains the geometric part of the vector layer, e.g., the `POLYGON` or `MULTIPOLYGON` geometries of the 177 countries in `dat`:
```{python}
dat["geometry"]
```
The geometry column also contains the spatial reference information, if any (see below).
Many of the spatial operators, such as calculating the centroid, buffer, or bounding box of each feature, in fact involve just the geometry.
Therefore, for example, the following expressions give exactly the same result, a `GeoSeries` with country bounding boxes:
```{python}
dat.bounds
```
```{python}
dat["geometry"].bounds
```
Another useful property of the geometry column is the geometry type (see below).
Note that the types of geometries contained in a geometry column (and, thus, a vector layer) are not necessarily the same.
Accordingly, the `.type` property returns a `Series` (of type `string`), rather than a single value:
```{python}
dat["geometry"].type
```
To summarize the occurrence of different geometry types in a geometry column, we can use the **pandas** method called `value_counts`:
```{python}
dat["geometry"].type.value_counts()
```
In this case, we see that the `dat` layer contains `Polygon` and `MultiPolygon` geometries.
### Geometries
Each element in the geometry column is a geometry object, of class `shapely`.
For example, here is one specific geometry selected by implicit index (that of Canada):
```{python}
dat["geometry"].iloc[3]
```
and here is a specific geometry selected based on the `"name_long"` attribute:
```{python}
dat[dat["name_long"] == "Egypt"]["geometry"].iloc[0]
```
The **shapely** package is compatible with the Simple Features standard.
Accordingly, seven types of geometries are supported.
The following section demonstrates creating a `shapely` geometry of each type, using a `string` in the WKT format as input.
First, we need to import the `shapely.wkt` module:
```{python}
import shapely.wkt as wkt
```
Then, we use the `wkt.loads` (stands for "load a WKT *s*tring") to transform a WKT string to a `shapely` geometry object.
Here is an example of a `POINT` geometry:
```{python}
point = wkt.loads("POINT (5 2)")
point
```
Here is an example of a `MULTIPOINT` geometry:
```{python}
multipoint = wkt.loads("MULTIPOINT ((5 2), (1 3), (3 4), (3 2))")
multipoint
```
Here is an example of a `LINESTRING` geometry:
```{python}
linestring = wkt.loads("LINESTRING (1 5, 4 4, 4 1, 2 2, 3 2)")
linestring
```
Here is an example of a `MULTILINESTRING` geometry:
```{python}
multilinestring = wkt.loads("MULTILINESTRING ((1 5, 4 4, 4 1, 2 2, 3 2), (1 2, 2 4))")
multilinestring
```
Here is an example of a `POLYGON` geometry:
```{python}
polygon = wkt.loads("POLYGON ((1 5, 2 2, 4 1, 4 4, 1 5), (2 4, 3 4, 3 3, 2 3, 2 4))")
polygon
```
Here is an example of a `MULTIPOLYGON` geometry:
```{python}
multipolygon = wkt.loads("MULTIPOLYGON (((1 5, 2 2, 4 1, 4 4, 1 5)), ((0 2, 1 2, 1 3, 0 3, 0 2)))")
multipolygon
```
And, finally, here is an example of a `GEOMETRYCOLLECTION` geometry:
```{python}
geometrycollection = wkt.loads("GEOMETRYCOLLECTION (MULTIPOINT (5 2, 1 3, 3 4, 3 2), LINESTRING (1 5, 4 4, 4 1, 2 2, 3 2))")
geometrycollection
```
`shapely` geometries act as atomic units of vector data, as spatial operations on a geometry return a single new geometry.
For example, the following expression calculates the difference between the buffered `multipolygon` (using distance of `0.1`) and itself:
```{python}
multipolygon.buffer(0.2).difference(multipolygon)
```
Internally, many spatial operations on a geometry column (or a vector layer) are basically iterations where the operator is applied on all geometries, one by one, to return a new geometry column (or layer) with the combined results.
As demonstrated above, a `shapely` geometry object is automatically evaluated to a small image of the geometry (when using an interface capable of displaying it, such as a Jupyter Notebook).
To print the WKT string instead, we can use the `print` function:
```{python}
print(linestring)
```
We can determine the geometry type using the `.geom_type` property, which is a `string`:
```{python}
linestring.geom_type
```
Finally, it is important to note that raw coordinates of `shapely` geometries are accessible through a combination of the `.coords`, `.geoms`, `.exterior`, and `.interiors`, properties (depending on the geometry type).
These access methods are useful for when we need to develop our own spatial operators for specific tasks.
For example, the following expression returns the coordinates of the `polygon` geometry exterior (note that the returned object is iterable, thus enclosed in a `list` to return all coordinates at once):
```{python}
list(polygon.exterior.coords)
```
## Raster data
### Introduction
As mentioned above, working with rasters in Python is less organized around one comprehensive package (such as the case for vector layers and **geopandas**).
Instead, there are several packages providing alternative (subsets of methods) of working with raster data.
The two most notable approaches for working with rasters in Python are provided by the **rasterio** and **xarray** packages.
As we will see shortly, they differ in their scope and underlying data models.
Specifically, **rasterio** represents rasters as **numpy** arrays associated with a separate object holding the spatial metadata.
The **xarray** package, however, represents rasters with the native `DataArray` object, which is an extension of **numpy** array designed to hold axis labels and attributes, in the same object, together with the array of raster values.
Both packages are not comprehensive in the same way as **geopandas** is. For example, when working with **rasterio**, on the one hand, more packages may be needed to accomplish (commonly used) tasks such as zonal statistics (package `zonalstats`) or calculating topographic indices (package `richdem`). On the other hand, **xarray** was extended to accommodate spatial operators missing from the core package itself, with the **rioxarray** and **xarray-spatial** packages.
In the following two sections, we introduce the two well-established packages, **rasterio** and **xarray**, which form the basis for most raster functionality in Python.
Using any of the add-on packages, or the extensions, should be straightforward, once the reader is familiar with the basics.
### Using **rasterio**
To work with the **rasterio** package, we first need to import it. We also import **numpy**, since (as we will see shortly), the underlying raster data are stored in **numpy** arrays.
To effectively work with those we therefore expose all **numpy** functions.
Finally, we import the `show` function from the `rasterio.plot` sub-module for quick visualization of rasters.
```{python}
import numpy as np
import rasterio
from rasterio.plot import show
import subprocess
```
Rasters are typically imported from existing files.
When working with **rasterio**, "importing" a raster is actually a two-step process:
* First, we open a raster file "connection", using `rasterio.open`
* Second, we read raster values from the connection using the `.read` method
This kind of separation is analogous to basic Python functions for reading from files, such as `open` and `.readline` to read from a text file.
The rationale is that we do not always want to read all information from the file into memory, which is particularly important as rasters size can be larger than RAM size.
Accordingly, the second step (`.read`) is selective. For example, we may want to read just one raster band rather than reading all band.
In the first step, to create a file connection, we pass a file path to the `rasterio.open` function.
For this example, we use a single-band raster representing elevation in Zion National Park:
```{python}
src = rasterio.open("data/srtm.tif")
```
To get a first impression of the raster values, we can plot it using the `show` function:
```{python}
show(src);
```
The "connection" object contains the raster metadata, that is, all of the information other than the raster values.
Let us examine it:
```{python}
src.meta
```
Importantly, we can see:
* The raster data type (`dtype`)
* Raster dimensions (`width`, `height`, and `count`, i.e., number of layers)
* Raster Coordinate Reference System (`crs`)
* The raster affine transformation matrix (`transform`)
The last item (i.e., `transform`) deserves a few more words.
To position a raster in geographical space, in addition to the CRS we must specify the raster *origin* ($x_{min}$, $y_{max}$) and resolution ($delta_{x}$, $delta_{y}$).
In the transform matrix notation, these data items are stored as follows:
```{text}
Affine(delta_x, 0.0, x_min,
0.0, delta_y, y_max)
```
Note that, by convention, raster y-axis origin is set to the maximum value ($y_{max}$) rather than the minimum, and, accordingly, the y-axis resolution ($delta_{y}$) is negative.
The `.read` method of a raster file connection object is used to read the last but not least piece of information: the raster values.
Importantly, we can read:
* A particular layer, passing a numeric index (as in `.read(1)`)
* A subset of layers, passing a `list` of indices (as in `.read([1,2])`)
* All layers (as in `.read()`)
Note that the layer indices start from `1` contrary to the Python convention of the first index being `0`.
The resulting object is a **numpy** array, with either two or three dimensions:
* *Three* dimensions, when reading all layers or more than one layer (e.g., `.read()` or `.read([1,2])`). In such case, the dimensions pattern is `(layers, rows, columns)`
* *Two* dimensions, when reading one specific layer (e.g., `.read(1)`)
For example, let us read the first (and only) layer from the `srtm.tif` raster, using the file connection object `src`:
```{python}
s = src.read(1)
s
```
### Using `xarray`
...
```{python}
import xarray as xr
```
Reading:
```{python}
x = xr.open_dataset("data/absolute_v5.nc")
x
```
```{python}
x["tem"]
```
Plot:
```{python}
x["tem"].plot(col="time", col_wrap=4)
```
## Coordinate Reference Systems
```{python}
dat.crs
```
```{python}
src.crs
```
## Exercises
...